I find print_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?
Note #tchrist recommends Data::Dump over Data::Dumper. I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to interpret results.
Data::Dumper :
A snippet of the examples shown in the above link.
use Data::Dumper;
package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
package Fuz; # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};
package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
{1 => 'a', 023 => 'b', 0x45 => 'c'},
\\"p\q\'r", $foo, $fuz];
########
# simple usage
########
$bar = eval(Dumper($boo));
print($#) if $#;
print Dumper($boo), Dumper($bar); # pretty print (no array indices)
$Data::Dumper::Terse = 1; # don't output names where feasible
$Data::Dumper::Indent = 0; # turn off all pretty print
print Dumper($boo), "\n";
$Data::Dumper::Indent = 1; # mild pretty print
print Dumper($boo);
$Data::Dumper::Indent = 3; # pretty print with array indices
print Dumper($boo);
$Data::Dumper::Useqq = 1; # print strings in double quotes
print Dumper($boo);
As usually with Perl, you might prefer alternative solutions to the venerable Data::Dumper:
Data::Dump::Streamer has a terser output than Data::Dumper, and can also serialize some data better than Data::Dumper,
YAML (or Yaml::Syck, or an other YAML module) generate the data in YAML, which is quite legible.
And of course with the debugger, you can display any variable with the 'x' command. I particularly like the form 'x 2 $complex_structure' where 2 (or any number) tells the debugger to display only 2 levels of nested data.
An alternative to Data::Dumper that does not produce valid Perl code but instead a more skimmable format (same as the x command of the Perl debugger) is Dumpvalue. It also consumes a lot less memory.
As well, there is Data::Dump::Streamer, which is more accurate in various edge and corner cases than Data::Dumper is.
I use Data::Dump, it's output is a bit cleaner than Data::Dumper's (no $VAR1), it provides quick shortcuts and it also tries to DTRT, i.e. it will print to STDERR when called in void context and return the dump string when not.
I went looking for the same thing and found this lovely little Perl function, explicitly meant to generate results like print_r().
The author of the script was asking your exact question in a forum here.
print objectToString($json_data);
Gives this output:
HASH {
time => 1233173875
error => 0
node => HASH {
vid => 1011
moderate => 0
field_datestring => ARRAY {
HASH {
value => August 30, 1979
}
}
field_tagged_persons => ARRAY {
HASH {
nid => undef
}
}
...and so on...
Related
All request and dumps in laravel add a ^before a result, that's only do that in dd or dump
This effect generate a lot of errors on my code, someone past some like that?
I had the same problem with laravel framework Lumen (5.8.12) and I solved the problem by returning to version 5.8.4.
The Origin of the problem seems to be the Symfony VarDumper Component
(\vendor\symfony\var-dumper\Cloner\Data.php, line 302):
$dumper->dumpScalar($cursor, 'default', '^');
Should be:
$dumper->dumpScalar($cursor, 'default', '');
Update
It is there for a useful reason. In terminal if you hover over the mouse on that ^ sign it will show you the file path from where this dump is coming from! I think it's really a useful thing but I don't see it working in browser. So, it should either be removed from borwser or fix the issue there.
For simple variables, reading the output should be straightforward. Here are some examples showing first a variable defined in PHP, then its dump representation:
Check This Link For Better reference
For example:
$var = [
'a simple string' => "in an array of 5 elements",
'a float' => 1.0,
'an integer' => 1,
'a boolean' => true,
'an empty array' => [],
];
dump($var);
The gray arrow is a toggle button for hiding/showing children of nested structures.
$var = "This is a multi-line string.\n";
$var .= "Hovering a string shows its length.\n";
$var .= "The length of UTF-8 strings is counted in terms of UTF-8 characters.\n";
$var .= "Non-UTF-8 strings length are counted in octet size.\n";
$var .= "Because of this `\xE9` octet (\\xE9),\n";
$var .= "this string is not UTF-8 valid, thus the `b` prefix.\n";
dump($var);
class PropertyExample
{
public $publicProperty = 'The `+` prefix denotes public properties,';
protected $protectedProperty = '`#` protected ones and `-` private ones.';
private $privateProperty = 'Hovering a property shows a reminder.';
}
$var = new PropertyExample();
dump($var);
I am trying to use the tablesorter pager plugin with AJAX but run into som problemes (or limitations) when trying to handle the AJAX request in my php backend.
If eg. the table is set up with a default sorting of
sortList: [ [0,1], [1,0] ]
I will get a URL like this on my AJAX request:
page=0&size=50&filter=fcol[6]=batteri&sort=col[0]=1&col[1]=0
In my php back end I do a
$cur_sort = $_GET['sort']
and get
col[0]=1
So the last part is missing - I guess since it contains a & char.
How do I get the entire sort string?
That said how is the string col[0]=1&col[1]=0 best parsed? I need to extract the info that col 0 is to be sorter DESC and col 1 ASC.
You can try this;
parse_str($_SERVER['QUERY_STRING'],$data);
It will parse the url to an array;
Also; you should use empty [] instead of [1] and [0]
See more here: parse_str()
Example:
$str = "page=0&size=50&filter=fcol[6]=batteri&sort=col[0]=1&col[1]=0";
parse_str($str, $output);
echo $output['page']; // echo 0
And to answer your question; it is correct; is echoing col[0]=1 because you are dividing with & see here:
&sort=col[0]=1 & col[1]=0;
An advice; use more names, instead.
You could use
&sort[]=1&sort[]=0;
UPDATE:
To access the last one; you should do, simply;
$_GET['col'][1];
If you want to access, the last number in
$_GET['sort'];
You can do this;
$explode = explode('=',$_GET['sort']);
$end = end($explode);
echo $end; //it will outout 1
If you print your entire query_String, it will print this;
Array
(
[page] => 0
[size] => 50
[filter] => fcol[6]=batteri
[sort] => col[0]=1
[col] => Array
(
[1] => 0
)
)
I'm not sure how the ajaxUrl option is being used, but the output shared in the question doesn't look right.
I really have no idea how the string in the question is showing this format:
&sort=col[0]=1&col[1]=0 (where did sort= come from?)
&filter=fcol[6]=batteri (where did filter= come from?)
If you look at how you can manipulate the ajaxUrl option, you will see this example:
ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}"
So say you have the following settings:
page = 2
size = 10
sortList is set to [[0,1],[3,0]] (1st column descending sort, 4th column ascending sort)
filters is set as ['','','fred']
The resulting url passed to the server will look like this:
http://mydatabase.com?page=2&size=10&col[0]=1&col[3]=0&fcol[2]=fred
The col part of the {sortList:col} placeholder sets the sorted column name passed to the URL & the fcol part of {filterList:fcol} placeholder sets the filter for the set column. So those are not fixed names.
If the above method for using the ajaxUrl string doesn't suit your needs, you can leave those settings out of the ajaxUrl and instead use the customAjaxUrl option to modify the URL as desired. Here is a simple example (I know this is not a conventional method):
ajaxUrl: "http://mydatabase.com?page={page}&size={size}",
// modify the url after all processing has been applied
customAjaxUrl: function(table, url) {
var config = table.config,
// convert [[0,1],[3,0]] into "0-1-3-0"
sort = [].concat.apply( [], config.sortList ).join('-'),
// convert [ '', '', 'fred' ] into "--fred"
filter = config.lastSearch.join('-');
// send the server the current page
return url += '&sort=' + sort + '&filter=' + filter
}
With the same settings, the resulting URL will now look like this:
http://mydatabase.com?page=2&size=10&sort=0-1-3-0&filter=--fred
This is my own best solution so far, but it's not really elegant:
if (preg_match_all("/[^f]col\[\d+]=\d+/", $_SERVER['QUERY_STRING'], $matches)) {
foreach($matches[0] AS $sortinfo) {
if (preg_match_all("/\d+/", $sortinfo, $matches)) {
if(count($matches[0]) == 2) {
echo "Col: ".$matches[0][0]."<br/>";
echo "Order: ".$matches[0][1]."<br/>";
}
}
}
}
It gives me the info I need
Col: 0
Order: 1
Col: 1
Order: 0
But is clumbsy. Is there a better way?
I am primarily a PHP developer and have limited experience with Perl.
I was tasked with writing a queue script in Perl which checks against a database, and that is all working out great.
The problem I have is that in the Perl script I need to include a database hostname and password.
Right now I have them hard coded, which works fine, but my PHP application uses a global PHP array which holds the database hostname and password.I'd like to be able to use this PHP array in my Perl script.
Here is my PHP array
<?php
return array(
'database' => array(
'master' => array(
'hostname' => 'fd35:4776:6804:2:a::1',
'password' => 'password'
),
'slave' => array(
'hostname' => 'fd35:4776:6804:2:2::2',
'password' => 'password',
'profile' => true
)
)
);
I've tried searching with Google and have read many random posts on line, but I have yet been able to come up with a solution.
Does anyone have any ideas which I could try? If I'm missing any additional input, let me know and I can provide it.
Edit
Hopefully I worded this properly. How would I go about including this PHP array file so that I can manipulate it with Perl?
Alternative solutions are welcome too!
You've discovered one of the many reasons why code makes for bad config files. You should move the information to an actual config file, and access that file from both that .php file and from Perl.
JSON would make a decent file format here.
{
"database": {
"master": {
"hostname": "fd35:4776:6804:2:a::1",
"password": "password"
},
"slave": {
"hostname": "fd35:4776:6804:2:2::2",
"password": "password",
"profile": true
}
}
}
The Perl code would be
use JSON::XS qw( decode_json );
open (my $fh, '<:raw', $config_path)
or die("Can't open config file $config_path: $!\n");
my $file; { local $/; $file = <$fh>; }
my $config = decode_json($file);
On the PHP side, just replace the contents of the file you showed in your post with code to read the config file. I don't know PHP, but it should be quite simple. A quick search shows it might be
return json_decode(file_get_contents($config_path));
It would be simple to provide a short PHP program that dumps the array to a file in JSON format. That file can then be read from Perl using the JSON module.
This is all that is necessary.
<?php
$array = include 'array.php';
$fh = fopen('array.json', 'w');
fwrite($fh, json_encode($array));
fclose($fh);
?>
The resultant JSON file can then be read in a Perl program, like so:
use strict;
use warnings;
use JSON 'from_json';
my $data = do {
open my $fh, '<', 'array.json' or die $!;
local $/;
from_json(<$fh>);
};
use Data::Dump;
dd $data;
output
{
database => {
master => { hostname => "fd35:4776:6804:2:a::1", password => "password" },
slave => {
hostname => "fd35:4776:6804:2:2::2",
password => "password",
profile => bless(do{\(my $o = 1)}, "JSON::XS::Boolean"),
},
},
}
There is PHP::Include, which uses a source filter to let you have PHP blocks in your Perl code to declare variables. It also has a read_file() function that applies such a filter to a single PHP file.
But it seems to expect that your PHP has assignments (e.g. $config = array('database' => array(...) and changes those to Perl variable declarations.
In a few minutes of playing with it, I couldn't get it to do anything useful with your PHP code that uses return.
If you want a more "native Perl" solution, you can pretty much* just search and replace all your "array(" and their matching ")" to "{" and "}". That'll give you a perl datastructure called a "hash of hashes" (note: Unlike PHP, Perl refers to arrays with integer indicies as arrays (and uses the # sigil to denote variables containing them), but refers to array-like things with string indicies as "hashes" (and uses the % sigil to denote variables containing them)). The Perl keywords/concepts you probably want to read up on are:
Perl Data Structures: http://perldoc.perl.org/perldsc.html
and specifically the Hash Of Hashes section: http://perldoc.perl.org/perldsc.html#HASHES-OF-HASHES
and if you dont understand what $hashref = \%hash and %hash{key} and $hashref->{key} mean in Perl, you'd want to read http://perldoc.perl.org/perlref.html
Example code (note how similar the getConfig subroutine is to your PHP code):
#!/usr/bin/perl
use strict;
use warnings;
my $config=getConfig();
print "Database master host = " . $config->{database}{master}{hostname};
print "\n";
print "Database master password = " . $config->{database}{master}{password};
print "\n";
print "Database slave profile = " . $config->{database}{slave}{profile};
print "\n";
sub getConfig{
return {
'database' => {
'master' => {
'hostname' => 'fd35:4776:6804:2:a::1',
'password' => 'password'
},
'slave' => {
'hostname' => 'fd35:4776:6804:2:2::2',
'password' => 'password',
'profile' => 'true'
}
}
};
}
I said "pretty much", because your sample data used the bare word 'true' for the slave->profile value - that's a syntax error in Perl - you can change it to a bare 1, or quote the value as "true" to make it work. In Perl, the digit zero, the string "0" or the empty/nul string "" all evaluate to "false" in a boolean context, anything else evaluates to "true". Take care if you choose to automate PHP to Perl translation, there may be other PHP-isms which could catch you out like that.
So much good information here and it helped me out quite a bit to come up with a working solution.
Here is the perl script I've got working:
#!/usr/bin/perl
use PHP::Include;
include_php_vars( 'config.local.php' );
my $test = \%config;
print $test->{'database'}->{'master'}->{'hostname'};
I also took the PHP array and changed it so that it no longer return array() but $config = array() and then return $config;
This did the trick for me. Thank you!
I have an object which has a state property, for example state = 'state4' or state = 'state2'.
Now I also have an array of all available states that the state property can get, state1 to state8 (note: the states are not named stateN. They have eight different names, like payment or canceled. I just put stateN to describe the problem).
In addition to that, I have a logical expression like $expression = !state1||state4&&(!state2||state5) for example. This is the code for the above description:
$state = 'state4';
$expression = '!state1||state4&&(!state2||state5)';
Now I want to check if the logical expression is true or false. In the above case, it's true. In the following case it would be false:
$state = 'state1';
$expression = state4&&!state2||(!state1||state7);
How could this be solved in an elegant way?
//Initialize
$state = 'state4';
$expression = '!state1||state4&&(!state2||state5)';
//Adapt to your needs
$pattern='/state\d/';
//Replace
$e=str_replace($state,'true',$expression);
while (preg_match_all($pattern,$e,$matches)
$e=str_replace($matches[0],'false',$e);
//Eval
eval("\$result=$e;");
echo $result;
Edit:
Your update to the OQ necessitates some minor work:
//Initialize
$state = 'payed';
$expression = '!payed||cancelled&&(!whatever||shipped)';
//Adapt to your needs
$possiblestates=array(
'payed',
'cancelled',
'shipped',
'whatever'
);
//Replace
$e=str_replace($state,'true',$expression);
$e=str_replace($possiblestates,'false',$e);
//Eval
eval("\$result=$e;");
echo $result;
Edit 2
There has been concern about eval and PHP injection in the comments: The expression and the replacements are completly controlled by the application, no user input involved. As long as this holds, eval is safe.
I am using ExpressionLanguage, but there are few different solutions
ExpressionLanguage Symfony Component - https://symfony.com/doc/current/components/expression_language.html
cons - weird array syntax - array['key']. array.key works only for objects
cons - generate notice for array['key'] when key is not defined
pros - stable and well maintainer
https://github.com/mossadal/math-parser
https://github.com/optimistex/math-expression
Please remember that eval is NOT an option, under NO circumstances. We don't live an a static world. Any software always grows and evolves. What was once considered a safe input an one point may turn completely unsafe and uncontrolled.
I think you have a case which can be solved if you model each of your expressions as a rooted directed acyclic graph (DAG).
I assumed acyclic since your ultimate aim is to find the result of boolean algebra operations (if cycling occur in any of graph, then it'd be nonsense I think).
However, even if your graph structure—meaningfully—can be cyclic then your target search term will be cyclic graph, and it should still have a solution.
$expression = '!state1||state4&&(!state2||state5)';
And you have one root with two sub_DAGs in your example.
EXPRESSION as a Rooted DAG:
EXPRESSION
|
AND
___/ \___
OR OR
/ \ / \
! S_1 S_4 ! S_2 S5
Your adjacency list is:
expression_adj_list = [
expression => [ subExp_1, subExp_2 ] ,
subExp_1 => [ ! S_1, S_4 ],
subExp_2 => [ ! S_2, S5 ]
]
Now you can walk through this graph by BFS (breadth-first search algorithm) or DFS (depth-first search algorithm) or your custom, adjusted algorithm.
Of course you can just visit the adjacency list with keys and values as many times as you need if this suits and is easier for you.
You'll need a lookup table to teach your algorithm that. For example,
S2 && S5 = 1,
S1 or S4 = 0,
S3 && S7 = -1 (to throw an exception maybe)
After all, the algorithm below can solve your expression's result.
$adj_list = convert_expression_to_adj_list();
// can also be assigned by a function.
// root is the only node which has no incoming-edge in $adj_list.
$root = 'EXPRESSION';
q[] = $root; //queue to have expression & subexpressions
$results = [];
while ( ! empty(q)) {
$current = array_shift($q);
if ( ! in_array($current, $results)) {
if (isset($adj_list[$current])) { // if has children (sub/expression)
$children = $adj_list[$current];
// true if all children are states. false if any child is subexpression.
$bool = is_calculateable($children);
if ($bool) {
$results[$current] = calc($children);
}
else {
array_unshift($q, $current);
}
foreach ($children as $child) {
if (is_subexpresssion($child) && ! in_array($child, $results)) {
array_unshift($q, $child);
}
}
}
}
}
return $results[$root];
This approach has a great advantage also: if you save the results of the expressions in your database, if an expression is a child of the root expression then you won't need to recalculate it, just use the result from the database for the child subexpressions. In this way, you always have a two-level depth DAG (root and its children).
I think example will be much better than loooong description :)
Let's assume we have an array of arrays:
("Server1", "Server_1", "Main Server", "192.168.0.3")
("Server_1", "VIP Server", "Main Server")
("Server_2", "192.168.0.4")
("192.168.0.3", "192.168.0.5")
("Server_2", "Backup")
Each line contains strings which are synonyms. And as a result of processing of this array I want to get this:
("Server1", "Server_1", "Main Server", "192.168.0.3", "VIP Server", "192.168.0.5")
("Server_2", "192.168.0.4", "Backup")
So I think I need a kind of recursive algorithm. Programming language actually doesn't matter — I need only a little help with idea in general. I'm going to use php or python.
Thank you!
This problem can be reduced to a problem in graph theory where you find all groups of connected nodes in a graph.
An efficient way to solve this problem is doing a "flood fill" algorithm, which is essentially a recursive breath first search. This wikipedia entry describes the flood fill algorithm and how it applies to solving the problem of finding connected regions of a graph.
To see how the original question can be made into a question on graphs: make each entry (e.g. "Server1", "Server_1", etc.) a node on a graph. Connect nodes with edges if and only if they are synonyms. A matrix data structure is particularly appropriate for keeping track of the edges, provided you have enough memory. Otherwise a sparse data structure like a map will work, especially since the number of synonyms will likely be limited.
Server1 is Node #0
Server_1 is Node #1
Server_2 is Node #2
Then edge[0][1] = edge[1][0] = 1, indicated that there is an edge between nodes #0 and #1 ( which means that they are synonyms ). While edge[0][2] = edge[2][0] = 0, indicating that Server1 and Server_2 are not synonyms.
Complexity Analysis
Creating this data structure is pretty efficient because a single linear pass with a lookup of the mapping of strings to node numbers is enough to crate it. If you store the mapping of strings to node numbers in a dictionary then this would be a O(n log n) step.
Doing the flood fill is O(n), you only visit each node in the graph once. So, the algorithm in all is O(n log n).
Introduce integer marking, which indicates synonym groups. On start one marks all words with different marks from 1 to N.
Then search trough your collection and if you find two words with indexes i and j are synonym, then remark all of words with marking i and j with lesser number of both. After N iteration you get all groups of synonyms.
It is some dirty and not throughly efficient solution, I believe one can get more performance with union-find structures.
Edit: This probably is NOT the most efficient way of solving your problem. If you are interested in max performance (e.g., if you have millions of values), you might be interested in writing more complex algorithm.
PHP, seems to be working (at least with data from given example):
$data = array(
array("Server1", "Server_1", "Main Server", "192.168.0.3"),
array("Server_1", "VIP Server", "Main Server"),
array("Server_2", "192.168.0.4"),
array("192.168.0.3", "192.168.0.5"),
array("Server_2", "Backup"),
);
do {
$foundSynonyms = false;
foreach ( $data as $firstKey => $firstValue ) {
foreach ( $data as $secondKey => $secondValue ) {
if ( $firstKey === $secondKey ) {
continue;
}
if ( array_intersect($firstValue, $secondValue) ) {
$data[$firstKey] = array_unique(array_merge($firstValue, $secondValue));
unset($data[$secondKey]);
$foundSynonyms = true;
break 2; // outer foreach
}
}
}
} while ( $foundSynonyms );
print_r($data);
Output:
Array
(
[0] => Array
(
[0] => Server1
[1] => Server_1
[2] => Main Server
[3] => 192.168.0.3
[4] => VIP Server
[6] => 192.168.0.5
)
[2] => Array
(
[0] => Server_2
[1] => 192.168.0.4
[3] => Backup
)
)
This would yield lower complexity then the PHP example (Python 3):
a = [set(("Server1", "Server_1", "Main Server", "192.168.0.3")),
set(("Server_1", "VIP Server", "Main Server")),
set(("Server_2", "192.168.0.4")),
set(("192.168.0.3", "192.168.0.5")),
set(("Server_2", "Backup"))]
b = {}
c = set()
for s in a:
full_s = s.copy()
for d in s:
if b.get(d):
full_s.update(b[d])
for d in full_s:
b[d] = full_s
c.add(frozenset(full_s))
for k,v in b.items():
fsv = frozenset(v)
if fsv in c:
print(list(fsv))
c.remove(fsv)
I was looking for a solution in python, so I came up with this solution. If you are willing to use python data structures like sets
you can use this solution too. "It's so simple a cave man can use it."
Simply this is the logic behind it.
foreach set_of_values in value_collection:
alreadyInSynonymSet = false
foreach synonym_set in synonym_collection:
if set_of_values in synonym_set:
alreadyInSynonymSet = true
synonym_set = synonym_set.union(set_of_values)
if not alreadyInSynonymSet:
synonym_collection.append(set(set_of_values))
vals = (
("Server1", "Server_1", "Main Server", "192.168.0.3"),
("Server_1", "VIP Server", "Main Server"),
("Server_2", "192.168.0.4"),
("192.168.0.3", "192.168.0.5"),
("Server_2", "Backup"),
)
value_sets = (set(value_tup) for value_tup in vals)
synonym_collection = []
for value_set in value_sets:
isConnected = False # If connected to a term in the graph
print(f'\nCurrent Value Set: {value_set}')
for synonyms in synonym_collection:
# IF two sets are disjoint, they don't have common elements
if not set(synonyms).isdisjoint(value_set):
isConnected = True
synonyms |= value_set # Appending elements of new value_set to synonymous set
break
# If it's not related to any other term, create a new set
if not isConnected:
print ('Value set not in graph, adding to graph...')
synonym_collection.append(value_set)
print('\nDone, Completed Graphing Synonyms')
print(synonym_collection)
This will have a result of
Current Value Set: {'Server1', 'Main Server', '192.168.0.3', 'Server_1'}
Value set not in graph, adding to graph...
Current Value Set: {'VIP Server', 'Main Server', 'Server_1'}
Current Value Set: {'192.168.0.4', 'Server_2'}
Value set not in graph, adding to graph...
Current Value Set: {'192.168.0.3', '192.168.0.5'}
Current Value Set: {'Server_2', 'Backup'}
Done, Completed Graphing Synonyms
[{'VIP Server', 'Main Server', '192.168.0.3', '192.168.0.5', 'Server1', 'Server_1'}, {'192.168.0.4', 'Server_2', 'Backup'}]