Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Seekers of Perl Wisdom

( #479=superdoc: print w/replies, xml ) Need Help??

If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
Minify HTML, CSS and JS Perl modules
1 direct reply — Read more / Contribute
by $h4X4_|=73}{
on Jan 21, 2017 at 05:25

    I have looked through some of the Perl modules that minify HTML, CSS and JS, But none do exactly what I want done.
    There are a few minify modules I have seen that come close HTML::Packer, CSS::Packer and JavaScript::Packer.
    Those modules will manly remove extra white-spaces and condense the markup or code so it can be downloaded faster.

    What I am looking for is a module that can compare HTML, CSS and JavaScript files. Then rebuild the HTML with only the CSS and JavaScript used in the HTML.
    Anyone know if this module exists?

    Update: The idea is to have the CSS and JavaScript used in the source of the HTML so no more files are needed for downloading, making the trip to the site faster.

Detecting 'our $foo => 1' mistake?
3 direct replies — Read more / Contribute
by perlancar
on Jan 21, 2017 at 04:58

    Dear monks,

    I just wasted half an hour trying to find a cause why a variable is undefined (and chasing the wrong rabbit of trying to figure out why a particular module won't load but require() doesn't raise an error), before finally realizing that I made a typo:

    our $foo => { a=>'blah', b=>'blah', ... };

    instead of:

    our $foo = { a=>'blah', b=>'blah', ... };

    And come to think of it, this is perhaps my third or fourth time being bitten by this. This mistake is not caught by warnings, so any suggestion on how to detect this? Perhaps there's a Perl::Critic policy somewhere and I need to just (re-)plunge and use Perl::Critic (again).

using waitpid() with signals
1 direct reply — Read more / Contribute
by ristov
on Jan 20, 2017 at 14:59

    I am trying to write the code which would wait for the child process to exit -- but if the code gets the TERM signal while waiting, the child process should be terminated with the same signal. While waiting for the child can be easily done with waitpid(pid, 0), signals do not interrupt waitpid() with EINTR error code. To solve this problem, one could use the following code with non-blocking waitpit():

    $term = 0; $SIG{TERM} = sub { $term = 1; }; for (;;) { $p = waitpid($pid, WNOHANG); # where did the child disappear? if ($p == -1) { exit(1); } # child has terminated if ($p == $pid && (WIFEXITED($?) || WIFSIGNALED($?))) { exit($?>>8); } # TERM has arrived, forward it to child and exit if ($term) { kill('TERM', $pid); exit(0); } # check the child again after 1 second sleep(1); }

    However, I am interested whether the same task can be accomplished with blocking waitpid() which consumes less CPU time. There is one very interesting recipe which involves the use of eval:

    http://blog.kazuhooku.com/2015/02/writing-signal-aware-waitpid-in-perl.html

    Nevertheless, I am wondering whether it would be OK to use the blocking waitpid() with a different signal handler for the same purpose:

    # waitpid($pid,WNOHANG) returns 0 if the child process # exists and has not terminated $SIG{TERM} = sub { waitpid($pid,WNOHANG) || kill('TERM', $pid); exit(0 +); } # waitpid loop for (;;) { $p = waitpid($pid, 0); # where did the child disappear? if ($p == -1) { exit(1); } # child has terminated if ($p == $pid && (WIFEXITED($?) || WIFSIGNALED($?))) { exit($?>>8); } }

    In the signal handler, waitpid($pid, WNOHANG) is used for checking if the child process exists, in order to avoid sending TERM to a non-existing process. Since I am not too familiar with Perl internals, I am not sure if it is OK if the signal handler is invoked in the middle of blocking waitpid(), in order to call waitpid() again in non-blocking mode from the handler. Can anyone provide some insights? If this approach has flaws, I would go with previous code examples.

    regards, risto
LibXML and %ENV in 5.18 on Windows
3 direct replies — Read more / Contribute
by gweekly
on Jan 20, 2017 at 12:11
    There seems to be a BUG in the interaction of XML::LibXML and delete $ENV{$variable}.
    This seems to have appeared in 5.18.
    Is this known?
    Is there a fix/solution?
    Have workarounds been posted?
    Thank you,
    -gordon

    
    # -*- perl -*-
    # badperl   19-Jan-2017 12:27 gweekly
    
    # Run on Windows
    #  for our 5.20.2:
    # >...\latest520\bin\perl i:\bin\badperl
    #  for 5.8.8:
    # >...\stable\bin\perl i:\bin\badperl
    
    use strict;
    use warnings;
    use XML::LibXML;
    
    # Pre-condition
    die "Please re-run having removed SAM from the environment\n"
        if grep { /^ SAM $ /xmsi} keys %ENV;
    
    # Set-up
    my ( $node )
        = XML::LibXML->new->parse_string(q{<xml><xyz name='SAM'/></xml>})
        ->documentElement
        ->find('child::*')
        ->get_nodelist;
    my ( $attr ) = $node->attributes; # eg: name=name,value=SAM
    my $name = $attr->value;
    
    my $fixed = substr "X$name", 1; # Should be the same
    
    # Confirm $name and $fixed appear to be as expected
    print "name is '$name', fixed is '$fixed'\n";
    die 'name is not SAM'  if $name ne 'SAM';
    die 'fixed is not SAM' if $fixed ne 'SAM';
    die 'fixed is not name' if $fixed ne $name;
    
    delete $ENV{$name}; # Here badness happens
    
    print defined $ENV{SAM}  ? "WRONG: ENV{SAM} is defined\n"
        :                       "OKAY: ENV{SAM} is not defined\n";
    print defined $ENV{$name} ? "WRONG: ENV{\$name} is defined\n"
        :                       "OKAY: ENV{\$name} is not defined\n";
    print exists $ENV{SAM}   ? "WRONG: ENV{SAM} exists\n"
        :                       "OKAY: ENV{SAM} does not exist\n";
    print exists $ENV{$name}  ? "WRONG: ENV{\$name} exists\n"
        :                       "OKAY: ENV{\$name} does not exist\n";
    
    if ( grep {$_ eq 'SAM'} keys %ENV ) {
        print "WRONG: ENV has the key 'SAM'\n";
    
        my $exists = exists $ENV{$fixed};
        print "Note: \$ENV{\$fixed} does " . ($exists?'':'NOT ') . "exist\n";
    }
    
    __END__
    
    # 5.8.8
    C:\Users\gweekly>...\stable\bin\perl i:\bin\badperl
    name is 'SAM', fixed is 'SAM'
    OKAY: ENV{SAM} is not defined
    OKAY: ENV{$name} is not defined
    OKAY: ENV{SAM} does not exist
    OKAY: ENV{$name} does not exist
    
    C:\Users\gweekly>c:\ActivePerl-5.14.2\bin\perl i:\bin\badperl
    name is 'SAM', fixed is 'SAM'
    OKAY: ENV{SAM} is not defined
    OKAY: ENV{$name} is not defined
    OKAY: ENV{SAM} does not exist
    OKAY: ENV{$name} does not exist
    
    C:\Users\gweekly>c:\ActivePerl5.16.3\bin\perl i:\bin\badperl
    name is 'SAM', fixed is 'SAM'
    OKAY: ENV{SAM} is not defined
    OKAY: ENV{$name} is not defined
    OKAY: ENV{SAM} does not exist
    OKAY: ENV{$name} does not exist
    
    C:\Users\gweekly>c:\ActivePerl5.18.1\bin\perl i:\bin\badperl
    name is 'SAM', fixed is 'SAM'
    OKAY: ENV{SAM} is not defined
    OKAY: ENV{$name} is not defined
    OKAY: ENV{SAM} does not exist
    WRONG: ENV{$name} exists
    WRONG: ENV has the key 'SAM'
    Note: $ENV{$fixed} does NOT exist
    
    C:\Users\gweekly>...\latest520\bin\perl i:\bin\badperl
    name is 'SAM', fixed is 'SAM'
    OKAY: ENV{SAM} is not defined
    OKAY: ENV{$name} is not defined
    OKAY: ENV{SAM} does not exist
    WRONG: ENV{$name} exists
    WRONG: ENV has the key 'SAM'
    Note: $ENV{$fixed} does NOT exist
    
    # Active-v5.24.1
    C:\Users\gweekly>perl i:\bin\badperl
    name is 'SAM', fixed is 'SAM'
    OKAY: ENV{SAM} is not defined
    OKAY: ENV{$name} is not defined
    OKAY: ENV{SAM} does not exist
    WRONG: ENV{$name} exists
    WRONG: ENV has the key 'SAM'
    Note: $ENV{$fixed} does NOT exist
    
Perl6::Form not printing 0 (zero)
2 direct replies — Read more / Contribute
by StuLong
on Jan 20, 2017 at 11:23

    I am using Perl6::Form, and have run into an issue wherein a numeric value of zero gets printed as octothorpes, as if the value is too large to fit the field. Happens for both single line and block format fields.

    Perl is v5.16.3 on RHEL7. Form is 0.06.

    use Perl6::Form; print form '{]].[}', [0,1];
    results in
    ###.## 1.0

    Field output is properly aligned on the decimal point, but the zero value field won't print. Anyone have any ideas how I can make my zeroes manifest themselves?

    Update. Things get weirder. After reading more in Perl6:Form docs, I tried one of the examples, and discovered that if I make the field in the example above slightly larger, the zeroes print, but are not properly formatted.

    print form '{]]].[}', [0,1]; 0.00. 1.0
Issues with Array of Hashes
2 direct replies — Read more / Contribute
by ciscomonkey
on Jan 20, 2017 at 10:54
    Having an issue with Text::CSV::Slurp not seeing my array of hashes. Here's some code that generates a hash just as my production script does:
    use Modern::Perl; use Text::CSV::Slurp; use Data::Dumper; sub generate { my %inline; $inline{'total'} = 2; $inline{'items'} = [ { 'name' => 'item1' }, { 'name' => 'item2' } ]; return \%inline; } my $ref = &generate(); print Dumper( $ref->{'items'} ); my $csv = Text::CSV::Slurp->create( input => $ref->{'items'} );
    I have multiple steps doing this same thing with no issue, and a quick Dumper output from those looks to be the exact same as the Dumper output from this code above. e.g. $VAR1 = [ {'key' => 'val' },{ 'key' => 'val' } ]; however it keeps coming back with "Need an an array of hashes input to create CSV from" and I'm a little lost as to why. I've even compared against those that work with the following:
    print "\$ref->{'items'} is " . ref( $ref->{'items'} ) . "\n"; foreach my $item ( @{ $ref->{'items'} } ) { print $item->{'name'} . " is " . ref( $item ) . "\n"; }
    Which yields:
    $ref->{'items'} is ARRAY item1 is HASH item2 is HASH
    And both look the same. I'm hoping I'm just missing something really simple here, but any help is appreciated.
Using an IO::File object stored in a Hash.
2 direct replies — Read more / Contribute
by jjs04
on Jan 20, 2017 at 10:47

    I have found something that I think should work, but does not work as expected. When I use Path::Class to open a file and save its handle to a variable, it works as expected.

    Sample 1:
    use Path::Class; my $filename = "data.txt"; my $handle = file($filename)->open('<:encoding(UTF-8)'); while (<$handle>) { chomp($_); print $_,"\n"; } close($handle);
    Sample 1 Output:
    1 2 3 4
    However, if I save the same in a hash, it does not. Sample 2:
    use Path::Class; my $filename = "data.txt"; my %hash = ( 'handle' => file($filename)->open('<:encoding(UTF-8)') ); while(<$hash{'handle'}>) { chomp($_); print $_,"\n"; } close($hash{'handle'});
    Sample 2 Output:
    IO::File=GLOB(0x6fdf28)
    What am I missing? I suspect it is something quite simple that I have not experienced before. Thank you for the assistance.

     

    Edit: As first indicated by BrowserUk, readline should be used. Because the diamond operator is used with readline and glob, there may be some ambiguity as to how the parser should proceed. When a hash element is used within the diamond operator (<$hash{$key}>), it is a glob, causing my difficulties.

    This following sample works as expected. Sample 4:
    use Path::Class; my $filename = "data.txt"; my %hash = ( 'handle' => file($filename)->open('<:encoding(UTF-8)') ); while(readline($hash{'handle'})) { chomp($_); print $_,"\n"; } close($hash{'handle'});
    Sample 4 Output:
    1 2 3 4
Constant code
4 direct replies — Read more / Contribute
by philiprbrenan
on Jan 20, 2017 at 10:26

    When I try:

    #!/usr/bin/perl sub aa{2} sub bb{2} my ($a, $b) = (aa, bb); my ($s, $t) = ((2*aa+bb), (2*$a+$b)); say STDERR "$a==", aa; say STDERR "$b==", bb; say STDERR "$s==$t";

    I get:

    2==2 2==2 4==6

    Please tell me what I am doing wrong, as I expected $s and $t to be equal

    It can't be perl It must be me Yet what it is I cannot see

    Thanks!

PERL searching through a file
2 direct replies — Read more / Contribute
by ssimone
on Jan 20, 2017 at 08:33
    Hi, i have this PERL problem that i need to solve. I need to write a PERL script, which receives the name of a file as a command line attributeARGV0. Then, through the keyboard, it should receive parameters, one by one(array of charachters) that need to be searched in the text from the file. The script should create new files (the number of new files should be the same as the number of parameters received from a keyboard) with the same name as the original file, but it needs to have "_parameter" where(instead of "parameter" it should be the actual name of the parameter). In those files, the script writes down the sentences where the searching parameter shows in the original file. Every sentence i seperated from another one with "." and/or a new line \n.
How to create array from file
2 direct replies — Read more / Contribute
by Mjpaddy
on Jan 20, 2017 at 07:11

    Hello All!

    I have a question, how to create array as follows:

    input file

    1 2 hello aerf 1 2 hello aerf 1 2 hello aerf 1 2 hello aerf 1 2 hello aerf 1 2 hello aerf
    $VAR1 = [ ['1,2,\'hello\',\'aerf\''], ['1,2,\'hello\',\'aerf\''], ['1,2,\'hello\',\'aerf\''], ['1,2,\'hello\',\'aerf\''], ['1,2,\'hello\',\'aerf\''], ['1,2,\'hello\',\'aerf\''] ];

    Really appreciate any help.

    use Data::Dumper; open FH, "sap.txt" or die "$!"; while(<FH>){ chomp $_; push(@data,$_); } print Dumper \@data; close FH; __DATA__ $VAR1 = [ '1 2 hello aerf', '1 2 hello aerf', '1 2 hello aerf', '1 2 hello aerf', '1 2 hello aerf', '1 2 hello aerf' ]; #now how I can convert this into the above output

Add your question
Title:
Your question:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":


  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others surveying the Monastery: (8)
    As of 2017-01-21 13:48 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      Do you watch meteor showers?




      Results (184 votes). Check out past polls.