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

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
strangeness with prototypes and 'logical defined or'?
No replies — Read more | Post response
by ed_hoch
on May 25, 2015 at 06:49

    on 5.16.2, why does

    perl -ce 'sub foo (&) {} foo {;} || 7'

    work just fine, while

    perl -ce 'sub foo (&) {} foo {;} // 7'

    gives compilation errors? this doesn't seem like a shell-escaping issue; if I copy it into a separate file, the same thing holds.



Appending a single Scalar after a match
2 direct replies — Read more / Contribute
by SavannahLion
on May 25, 2015 at 04:36

    So I found myself updating an old script (parses oodles of HTML files). and unknowingly introduced a subtle bug.
    Here is a condensed version of the original code. The match is irrelevant.

    my $k = ''; # A bunch of junk happens to this scalar before this point my $t = "\ttest \n \n"; ($k) = $t =~ /^\s*(.*?)\s*$/g; print $k ."\n";

    Without thinking, I made a subtle change.
    my $k = ''; # A bunch of junk happens to this scalar before this point my $t = "\ttest \n \n"; ($k) .= $t =~ /^\s*(.*?)\s*$/g; print $k ."\n";

    A '1' kept getting shoved into $k. Goes without saying that I spend hours chasing this new bug down until I realized I was trying to use a list in a scalar context. So after much cursing I went and fixed the bug like thus.
    my $k = ''; # A bunch of junk happens to this scalar before this point my $t = "\ttest \n \n"; $t =~ /^\s*(.*?)\s*$/g; ($k) .= $1; print $k ."\n";

    After a fashion, I got to thinking. Is there a way to get it back to a one liner again and still append the value of $1 to $k? I tried several variations on the original but can't seem to work out a solution. My thought was something along the lines of:
    my $k = ''; # A bunch of junk happens to this scalar before this point my $t = "\ttest \n \n"; ($k) .= $($t =~ /^\s*(.*?)\s*$/g)[0]; print $k ."\n";

    I tried several variations but I can't quite seem to get it right. My gut says it should be feasible, but my brain can't quite put it together
    Any ideas?

Reading file into two arrays
2 direct replies — Read more / Contribute
by subr01
on May 25, 2015 at 04:01
    If the file is: 1 http:/abcd efgh/ .. 2 http:/ .. I want one array to store 1 and 2. The second array should contain two elements having the two addresses. Since there is a space between address, using split function does not seem feasible. What should I do? This is my required output. $array[0] = 1 $array1 = 2 $arraynew[0] = http:/abcd efgh/ .. $arraynew1 = http:/ ..
Applying multiple file modes
4 direct replies — Read more / Contribute
by leelu
on May 24, 2015 at 21:12


    Need help to fix the below error.

    I m trying to write a file twice in the same script. Both the time i m trying to append the o/p file

    $file = aaa.txt first time file mode open( my $testfile, "+>> $file" ) $!\n"; if ( -z "$testfile" ) ---> checking for empty file { write some o/p data close( $testfile );

    second time time file process

    open( my $testfile, "+>> $file" ) $!\n"; ---- ---- some condition check now adding some other info to the existing file close the file


    First read is working for second read unable to open the file and appending the records.

translate to one-liner
2 direct replies — Read more / Contribute
by j--a
on May 24, 2015 at 20:14

    Greetings Monks,

    Is there a module or standard program which translates scripts/programs/files into one-liner formats?

store/query semi-structure data
3 direct replies — Read more / Contribute
by Hosen1989
on May 24, 2015 at 16:33

    Dear ALL, We had application written in perl that create complex data structure for our subscriber (we have move than 4m subscribers).
    each subscriber have some conmen fields that are are present in all of them and some other subscriber has missing some.
    the data looks like the next:

    %subscribers = { "user_001" = { "name" => "sam", "age" => "13", "color" =>['red','blue'] "item"=>{ "old" =>['PC','pen'], "new" =>['tap','car'] }, "user_002" = { "name" => "ali", "age" => "54", "color" =>['red','null','green'] "item"=>{ "old" =>['phone','TV'] }, "user_003" = { "name" => "foo", "age" => "02", "item"=>{ "old" =>[''] }, .... } } #[our data are more nasty and complex]

    now we try to store these data in DB then do some query in them like get user that have new 'TAPs' in item or there age is larger than 30 years.
    what we need to know is:
    What is the best method to store the data (as MySQL or Oracle db not option), we need something for semi-structure data.
    How to do these queries taken in mind the preformence.

    We jast need headline to start our search (and yes we did our homework using Google ^_^).


[Solved] : Perl Serialization + Moose Object. Will the code get serialized?
1 direct reply — Read more / Contribute
by sam_bakki
on May 24, 2015 at 09:24

    Hi Monks,

    I am confused in the Perl object serialization (or serialization in general) topic. Please shed some light and enlighten me.

    I understand that perl serialization (using Storable module for example) can perfectly do the object / variables-value serialization. This means that, if I serialize a Moose class (ofcourse object), all the properties / variable values will be saved in a file and I can get them later to reconstruct the Moose object.

    I also understand that, the code part (Subs) can not be / will not be by default serialized. When we talk about Object Oriented Programming, The object contains two parts

    1. Data
    2. Procedure / function to operate on the Data

    I thought only Data part will be serialized. But I am wrong, To illustrate my confusion, Please see my example code below,

    package MooseClass; file use strict; use warnings; use Moose; use namespace::autoclean; #--------ONLY for Eclipse ---- #Just for the Perl Eclipse IDE to auto complete $self variable #$self = MooseClass->new(); #--------ONLY for Eclipse ---- # Members has 'name',is=>'rw',isa=>'Str',required=>1; has 'age',is=>'rw',isa=>'Int',required=>1; has 'gender', is=>'rw', isa=>'Str', required=>0; sub BUILD { my $self = shift @_; my $constArgsHashRef = shift @_; # Hash ref of arguments passed to + constructor at the time of object creation return 1; } sub increaseAge { my $self = shift @_; $self->age($self->age()+1); print "\n ", $self->name(), " is now ",$self->age()," old. "; return 1; } sub getAgeIterator { my $self = shift @_; my $iter = sub { print "\n iterate to next age", " AgeNow: ",$ +self->age(); return $self->age($self->age()+1); }; return $iter; } #Do it for all classes so Moose will create fast object creation, so a +pplication runs faster __PACKAGE__->meta->make_immutable(); no Moose; 1; use strict; use warnings; use Storable; use MooseClass; use Data::Dumper; my $obj = MooseClass->new(name=>'Eva',age=>'20',gender=>'girl'); print "\n Class dump \n", Dumper($obj); $obj->increaseAge(); print "\n Class dump 2\n", Dumper($obj); my $nextage = $obj->getAgeIterator(); $nextage->(); $nextage->(); print "\n Class dump 3\n", Dumper($obj); #Lets serailize the $obj store ($obj,'serialize.bin'); #Lets deserialize the object #--------ONLY for Eclipse ---- #Just for the Perl Eclipse IDE to auto complete $self variable #$newObj = MooseClass->new(); #--------ONLY for Eclipse ---- my $newObj = retrieve ('serialize.bin'); print "\n \n New Class dump1 \n", Dumper($newObj); $newObj->increaseAge(); print "\n \n New Class dump2 \n", Dumper($newObj); my $newnextAge = $newObj->getAgeIterator(); $newnextAge->(); $newnextAge->(); print "\n \n New Class dump3 \n", Dumper($newObj);

    #Output Class dump $VAR1 = bless( { 'name' => 'Eva', 'age' => '20', 'gender' => 'girl' }, 'MooseClass' ); Eva is now 21 old. Class dump 2 $VAR1 = bless( { 'name' => 'Eva', 'age' => 21, 'gender' => 'girl' }, 'MooseClass' ); iterate to next age AgeNow: 21 iterate to next age AgeNow: 22 Class dump 3 $VAR1 = bless( { 'name' => 'Eva', 'age' => 23, 'gender' => 'girl' }, 'MooseClass' ); New Class dump1 $VAR1 = bless( { 'gender' => 'girl', 'age' => 23, 'name' => 'Eva' }, 'MooseClass' ); Eva is now 24 old. New Class dump2 $VAR1 = bless( { 'gender' => 'girl', 'age' => 24, 'name' => 'Eva' }, 'MooseClass' ); iterate to next age AgeNow: 24 iterate to next age AgeNow: 25 New Class dump3 $VAR1 = bless( { 'gender' => 'girl', 'age' => 26, 'name' => 'Eva' }, 'MooseClass' );

    I thought $newObj (which is de-serialized), Can not call the class methods (Closure also working !). How its possible? This means, I can send this object to some other perl script / process which does not "use" the MooseClass and can it operate on the class member functions? So the serialization by default embeds the moose class member function code as well?

    forgive me, If I miss the obvious.

    Thanks & Regards,
    Bakkiaraj M
    My Perl Gtk2 technology demo project - , contributions are welcome.

best method in perl to execute command on remote server and fetch its output
2 direct replies — Read more / Contribute
by janasec
on May 24, 2015 at 09:02

    hi , I need to execute perl commands on remote systems and fetch the output,what is it which is convenient ssh,rsh or TELNET.

    I need to run several commands in a order and gather the output on several servers

    I also need to save the output of each command executed

Another 64-bit Perl bug. Is it fixed post 5.18?
4 direct replies — Read more / Contribute
by BrowserUk
on May 24, 2015 at 07:38

    The regex engine silently fails to process strings longer than 2**31 bytes on 64-bits perl's upto and including v5.18.4:

    $x = "the quick brown fox\n"; $x x= 107374182; print length $x;; 2147483640 + ### 8 bytes less than 2^31. $n=0; ++$n while $x =~ m[^.*$]mg; print $n;; + ### finds all the lines. 107374182 $x .= "the straw that broke the camel's back\n"; print length $x;; + ### Add another line that pushes the length a few bytes over 2^ +31 2147483678 $n=0; ++$n while $x =~ m[^.*$]mg; print $n;; + ### and it silently fails to find any of them. 0

    Before I raise a perlbug, does this fail on later perls? Does it fail on non-windows perls?

    If its been fixed already, which version did the fix happen?


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
retrieve data from array empty
2 direct replies — Read more / Contribute
by pverstraten
on May 24, 2015 at 05:07
    I'm relatively new to Perl, but I'm trying to retrieve data from mysql. The first statement is working fine. But in the second statement, it always retrieves "0", which of course is not the case. If I enter the statement in phpMyAdmin it retrieves the correct data. The problem is that I can't get the correct data. Any hints on this? My (stripped) code:
    #!/usr/bin/perl use DBI; $DBH = DBI->connect("DBI:mysql:database=$DB_DATABASE;host=$DB_SERVER", +$DB_USER,$DB_PASS); my $lastmonth=$mon-1; my $statement = "select from fte_intra.debiteuren deb where deb +.type='sms' AND (deb.Afloop_contract='0000-00-00' OR month(deb.Afloop +_contract)='$lastmonth') group by order by"; my $sth = $DBH->prepare($statement); $sth->execute(); while (my $ref = $sth->fetchrow_hashref()) { $invoice_cid = $ref->{'id'}; my $statement = "select mc.cid,mc.mail_month from gmsms.mail_count + mc where mc.cid = '$invoice_cid' AND mc.month='$lastmonth' AND +ar='$yearG'"; my $sth = $DBH->prepare($statement); $sth->execute(); toLog("$statement"); while(my $mc = $sth->fetchrow_array()) { $invoice_mccid = $mc->{'cid'}; toLog("In table: $invoice_mccid"); if ($invoice_mccid) { $invoice_mail_month = $mc->{'mail_month'}; toLog("In table: $invoice_mail_month"); } else {$invoice_mail_month = '0'}; toLog("Niet in table: $invoice_mail_month"); } toLog("INVOICE: $invoice_number [CID: $invoice_cid / MAIL: $invoic +e_mail_month]");

Add your question
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!
  • 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
  • Outside of code tags, you may need to use entities for some characters:
            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?

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

    How do I use this? | Other CB clients
    Other Users?
    Others perusing the Monastery: (7)
    As of 2015-05-25 10:53 GMT
    Find Nodes?
      Voting Booth?

      In my home, the TV remote control is ...

      Results (480 votes), past polls