Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

The Monastery Gates

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

Donations gladly accepted

If you're new here please read PerlMonks FAQ
and Create a new user.

New Questions
Finding node with attribute XML::LibXML
2 direct replies — Read more / Contribute
by jjap
on Sep 30, 2014 at 13:42
    Dear Monks,

    I am navigating a nested XML data structure and at some point, I want to retrieve the value of a tag having a specific attribute. I cannot figure out why I am not getting anything from the minimal reproducible below (return 0).

    use strict; use XML::LibXML; my $parser = XML::LibXML->new; my $doc = $parser->parse_file("minimal.xml"); my @vol = $doc->findnodes(q {Volume[@VolumeCategory="L"]}); # also tried various quoting scheme... my $tmp = scalar(@vol); print "Number of entries: $tmp \n"; # 0
    minimal.xml
    <root> <ProductKey>99</ProductKey> <Volume VolumeCategory="L" MeasurementCategory="Real">0.063</Volume> <Volume VolumeCategory="cuft" MeasurementCategory="Real">2.2</Volume> </root>
    Any hints would be greatly appreciated!

    Update: Thanks to both Ikegami and Toolic for great pointers.
    Also did some spelling edit.

pipe list open trouble?
1 direct reply — Read more / Contribute
by dk
on Sep 30, 2014 at 09:01
    Hello all,

    Can anybody explain why I'm seeing the difference in those pieces of code? I thought these should be identical:

    $ perl -e 'open F, @ARGV or die $!' '|-' echo 42 No such file or directory at -e line 1. $ perl -e 'open F, $ARGV[0],$ARGV[1],$ARGV[2] or die $!' '|-' echo 42 42
    Thank you!
timelocal error wired behaviour
3 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 30, 2014 at 02:44
    Hi Monks,

    I am getting a date input from a csv file, which i want to check each date with current date, and if older than 1 month, i can do some operation on it for that entry.

    I am not allowed to install extra libs so, i am not using Date::Calc and have to somehow stick to Time::Local.

    Here is the snippet of my code, and suggest where I am going wrong.

    Code :

    if (my ($inpmm, $inpdd, $inpyyyy) = @date[1] =~ '(\d+)/(\d+)/(\d+)') { { print "@date[1] : Has been split to $certyyyy, $certmm, $certdd"; my @certdate=(0, 1, 1, $certdd, $certmm-1, $certyyyy); print "---@certdate"; # Just to see how it gets formed my $inptime=timelocal_nocheck(@certdate); print "<td>$inptime</td>"; my $timediff=$inptime - $lmtime; print "$timediff"; if ($timediff <= 2628000) { <<Go with Job>> } else { <<Skip Job>> } } else { print "Not in Format" }

    Output

    08/12/2016 : Has been split to 2016, 08, 12---0 1 1 12 7 2016

    After this, it ubruptly ends, even when i have some 100 odd entries to go.

    Thanks a lot in advance

String::MkPasswd still supported?
5 direct replies — Read more / Contribute
by Skeeve
on Sep 30, 2014 at 01:25

    Recently I needed a function to generate passwords so instead of writing my own I did a CPAN search and found String::MkPasswd.

    Unfortunately the function simply increases the number of lower case letters if you don't give enough minimum characters of each class. Example: If you want at least 2 lower case letters and 2 upper case letters and 8 characters length, you always end up with 2 upper case and 6 lower case letters.

    I think this isn't too good so I created a pull request which will spread the missing 4 characters over all character classes.

    Now I'm wondering whether or not the module is still supported as there seems to be nothing happening.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Hash of subroutines as member of a class
3 direct replies — Read more / Contribute
by Hameed
on Sep 29, 2014 at 21:18
    Hi PerlMonks,

    It maybe a simple thing, but I seem to have hit a brick wall.

    I have a very simple class and in the constructor, I am creating a hash that is holding references to subs which are members of the same class as well.

    see below:
    package EOYStats; use strict; use warnings; use Data::Dumper; sub new { my $class = shift; my $this = bless {}, $class; $this->{ACT} = shift; %{ $this->{ACTIVITIES} } = ( 'Sale' => { 'func' => \&total_sold, 'datefield' => "date_sold", }, 'Purchae' => { 'func' => \&total_bought, 'datefield' => "date_bought", }, ); return $this; } sub get_stats { my $this = shift; my $arg = shift; $this->{ACTIVITIES}->{$this->{ACT}}->{'func'}->($arg); } sub total_sold { my $this = shift; my $arg = shift; $this->dosomething(); } sub total_bought { my $this = shift; my $arg = shift; # Do stuff.... } sub dosomething { my $this = shift; print "This is test...\n"; } return 1;
    Now, when I call total_sold from another method in this class (get_stats in this case), '$this' is undefined in total_sold and '$this->dosomething' returns an error 'Can't call method "dosomething" on an undefined value at EOYStats.pm line 37.'

    There is no real need to have these methods in a hash. I can simply write conditions in the get_stats and call the methods accordingly, but I wanted to try and see if this worked.

    so is it really ridiculously bad idea to do this or is it not possible or simply silly thing to do?

    Sorry if this is too confusing.

open and read file using cgi perl
2 direct replies — Read more / Contribute
by vivek.vivek
on Sep 29, 2014 at 11:29

    Hi, I have 2 files as below

    a.txt: LOCK xxx yyy 123 1.1 fff LOCK nnj hhh 789 2.2 uuu
    b.txt: LOCK xxx yyy 567 1.1 fff LOCK nnj hhh 000 2.2 uuu LOCK YUI hhh 520 2.3 ujk

    I am comparing both files by browsing it through a webpage and parsing the file. I need to compare the lines if only it starts with word LOCK and output the data. The code is doing the comparison, but my problem is that the output is repeated with the count of number of lines in each file.

    Eg: if a is compared with b, output repeted twice. if b is compared with a, output is repeated 3 times.

    my @files = ($file,$file1); open(INOUT1,"<", $file1) or die "cant open output file "; + while ($linea = <INOUT1>){ open(INOUT,"<", $file) or die "cant open output file"; while ($line = <INOUT>){ chomp $linea; next unless $linea =~ m/^LOCK /; chomp $line; next unless $line =~ m/^LOCK /; foreach $file_n (@files){ $old = $files[0]; $new = $files[1]; if ($old eq $file_n){ @words=split(/\s+/,$line); $feature1[$i]=$words[1]; $ver1[$i]=$words[3]; $exp1[$i]=$words[4]; $no1[$i]=$words[5]; $i++; } else{ @words=split(/\s+/,$linea); $feature2[$ii]=$words[1]; $ver2[$ii]=$words[3]; $exp2[$ii]=$words[4]; $no2[$ii]=$words[5]; $ii++; } } }close INOUT; }close INOUT1; print "<table border =1 align='left' style='font-family:Georgi +a;'> for ($b=0;$b<@feature1;$b++) { $test=0; for($a=0;$a<@feature2;$a++) { if($feature1[$b] ne $feature2[$a]) { $test++; } if($test == @feature2) { print "<tr><td>$feature1[$b]</td><td>$ +ver1[$b]</td><td>$exp1[$b]</td><td>$no1[$b]</td></tr>"; #$test++; } } } print "</table>"; print "<table border=1 align='left' style='font-family:Georgia +;'> for ($b=0;$b<@feature2;$b++) { $test=0; for($a=0;$a<@feature1;$a++) { if($feature2[$b] ne $feature1[$a]) { $test++; } if($test == @feature1) { #print $test; print "<tr><td>$feature2[$b]</td><td>$ver2 +[$b]</td><td>$exp2[$b]</td><td>$no2[$b]</td></tr>"; } } } print "</table>";}
Choosing an AWS S3 CPAN module
1 direct reply — Read more / Contribute
by sm@sh
on Sep 29, 2014 at 04:54
    I have a simple requirement to read a file from an S3 bucket. We'll be using access key + secret IAM authentication. I can find these modules on CPAN: * Net::Amazon::S3 * Amazon::S3 * AWS::S3 The first of these seems to be most common, and well-maintained. The w +eight of dependencies isn't a major problem given we already have man +y of them in our app. However, they are all quite bloated for my requirements, and from the +AWS docs, it is simply a case of generating an auth token to access t +he file. Can anyone recommend any other modules, or has written their own acces +s code?
How to make a timer with breaks
2 direct replies — Read more / Contribute
by xdfreaknikdx
on Sep 28, 2014 at 19:06

    (Hi I need to add countdown timer to my perl program which starts from 00:01:00(1 minute)when I start running the script and in every 00:00:10 (10 seconds) the timer stops and the program will asks if you want to continue or stop the countdown. Thanks in advance.)

Variable not set properly in perl
3 direct replies — Read more / Contribute
by sar123
on Sep 28, 2014 at 11:50
    I have the following code:
    #!/usr/bin/perl -w use warnings; use diagnostics; open $fh , "<", "$ARGV[0]" or die "Could not open file: $!"; sub getsub{ my $sub = $_[0]; print "sub entered for $sub\n"; while (<$fh>) { if (/\.subckt $sub/../\.ends/) { print ; } } } while (<$fh>) { if ($_ =~ /^xa1/) { $line = $_; print "line found to be $line\n"; while ((my $nxt = readline($fh)) =~ /^\+/) { $line = $nxt; print "line changed to $line\n"; } $line =~ s/\s+$//; print "last line is $line\n"; my $sub = (split '\s', $line)[-1]; print "subcircuit found is $sub in $line\n"; getsub($sub); } }
    Here I am trying to print some text between two patterns inside the `getsub` routine. But when I try to run this I enter the subroutine but doesn't enter the if block inside the subroutine. I am trying to run it on the following file:
    .subckt a1 x y z xa a b c1 xb c d e1 xc f g h1 .ends .subckt c1 x y z xa a b f xb c d e xc f g h .ends .subckt e1 x y z xa a b c1 xb c d k1 xc f g h1 .ends xa1 a s f a1
    I want to print the contents of the file between ".subckt a1" till ".ends".
    I know this could be done by the one liners of perl on the command line, but I want to create some generalized script for different files so I need to go this way only. What is wrong with the above code.
Best practices for handling errors
7 direct replies — Read more / Contribute
by v_melnik
on Sep 27, 2014 at 07:31

    Dear colleagues,

    I think, it's a matter of religion, but I'd like to get to know more on how other people, more experienced, prefer to handle errors/exceptions in respect to the structure of your programs.

    Let me describe how I'm doing it now and, if you have some time to share your experience, I'd be very grateful to you for describing how do you prefer to do it.

    My own "rules" for myself are quite simple.

    1. Don't die() while executing a subrotine or method. Only the main module can die() if something goes wrong. Nobody can predict where the class will be used, so an unexpected die() can break the caller's logic.
    2. If I've got an exception inside of a subroutine, the subroutine may return(undef). If everything's fine, it return's some value (it can be true or false - no matter), but if some error has been occuried (e.g. if we can't get data from the database), the undef shall be returned.

    That's okay, but how to let the caller know what's happened with the subroutine? As I think, the caller must have some explaination to be able to write something to the log-file or to show the error message to the operator. So, there is one more rule.

    1. Any class may have the "errstr" attribute, so if its' methor returned undef, the caller may get the explaination from this attribute.

    So, usually it looks like this:

    package SomeClass; #... sub some_method { # ... eval { die("Oops!"); }; if($@) { $self->{'errstr'} = "Something has gone wrong: $@"; return(undef) } # ... } #... package main; #... my $result = $obj->some_method; unless(defined($result)) { die("Can't SomeClass->some_method(): $obj->{'errstr'}"); } #...

    And, when something goes wrong, I can get something like that:

    Can't SomeClass->some_method(): Can't AnotherClass->another_method(): Can't OtherClass->other_method(): Can't open(): No such file at script.pl line 666.

    Frankly speaking, I have a persistent feeling that there are some other, much more elegant way to do it. And I hate how the final error message looks like. Just like "can't A, because can't B, because can't C, because f*** you". Ugh... :(

    And there is another annoying thing: I have to use die() in the constructor of an object (I mean new()), because if the constructor returns undef, the caller doesn't have an access to the object's "errstr" attribute at all (as we don't have the object bless()ed). So I have to always call constructors from eval()-blocks and get the explaination from $@.

    package SomeClass; #... sub new { # ... eval { die("Oops!"); }; if($@) { die("Something has gone wrong: $@"); } # ... } #... package main; #... my $obj = eval { $obj->new }; unless(defined($obj)) { die("Can't SomeClass->new(): $@"); } #...

    I absolutely hate it, but I don't see better ways to let the caller know why the object hasn't been blessed.

    Maybe I should consider using some global variable to keep the reference to the stack of errors occuried? What do you think?

    Maybe I should always die() (or confess() - as a better way to get to know who has called whom) inside of any method and call every method inside of eval()- or try()-block?

    I'll be very grateful to each of you for sharing your best practices on this matter. It really makes me feel unsatisfacted. :)

    Have a nice time!

    V.Melnik
Taint and Shellshock
5 direct replies — Read more / Contribute
by kennethk
on Sep 26, 2014 at 20:59

    Obviously, the correct way to deal with Shellshock is update bash. However, given that running under Taint mode already requires you to clean up pathing variables before external calls, would it be reasonable to shift best practice to invoking local %ENV = (PATH => '/usr/local/bin'); rather than piecemeal cleanup? Is there any good reason to not wipe the whole %ENV hash before an external call in web context?


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

find unique values from a file by comparing two columns
3 direct replies — Read more / Contribute
by sreeragtk86
on Sep 26, 2014 at 07:08
    Hi,

    I am trying to get the unique values from the combination of columns 2 & 3 (: as delim) .

    eg; below is the sample file
    D1:111:92111 D2:112:92111 D3:111:92111 D4:112:92111 D5:111:90222 D6:112:90222 D7:111:90222 D8:112:90222
    The output should be

    92111 has unique values 111,112

    90222 has unique values 111,112

    Regards
New Meditations
The importance of avoiding the shell
5 direct replies — Read more / Contribute
by jhourcle
on Sep 25, 2014 at 07:34

    For those who haven't heard, there was a Bash exploit announced yesterday. Although a patch did come out (4.3.25), there are reports that it does not fully fix the problem.

    Using variations of the test string that was posted to slashdot, it looks as if perl makes your system invulnerable:

    sh-3.2$ env x='() { :;}; echo vulnerable' sh -c "echo this is a test" vulnerable this is a test sh-3.2$ env x='() { :;}; echo vulnerable & echo' perl -e 'system "echo + test"' test sh-3.2$ env x='() { :;}; echo vulnerable' perl -e 'print `echo test`' test

    ... but unfortunately, perl only protects you when you either pass system a list. In other cases, if it sees a shell meta character in your string, you're still vulnerable:

    sh-3.2$ env x='() { :;}; echo vulnerable' perl -e 'print `echo test;`' vulnerable test sh-3.2$ env x='() { :;}; echo vulnerable' perl -e 'system "echo test;" +' vulnerable test sh-3.2$ env x='() { :;}; echo vulnerable' perl -e 'system qw(echo test +;)' test;

    Your main attack vector is CGIs -- anyone can set their user-agent, or pass in a query string, and the webserver will set environmental variables automatically. Should your scripts shell out, they're exploitable.

    So, the moral of the story: always use the list form of system, and avoid backticks if you can. If you have to do strange things w/ redirecting output, look at IPC::Open2 and IPC::Open3 which can also take list inputs.

New Monk Discussion
Daily Best Thread?
4 direct replies — Read more / Contribute
by QM
on Sep 29, 2014 at 05:01
    Being a somewhat erratic reader here, I find the Daily/Weekly/Monthly Best Nodes helpful to find high quality content in my limited time. (AFAIK, Daily Best does not have it's own page, but is derived from Best Nodes, and there's more info at About the Daily Best Nodelet.)

    But I often feel I'm missing out on the OPs that have lots of good discussion, while not making it into Best Nodes.

    My question: Is there a "Best Thread" mechanism? If not, is there enough interest to consider making one?

    Of course, this begs the question of what a "Best Thread" is, because we don't vote on threads. Given the current scheme, we'd have to compute some thread score, such as Sum_of_Node_Votes / Number_of_Nodes. Perhaps throw in a multiplier for unique responders, or unique readers.

    I did a quick search here, but of course "thread" comes up with the other kind, and I didn't find anything relevant. Please point me to any previous discussions.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2014-10-01 00:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (386 votes), past polls