Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

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
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]");
Need to append and replace for % sign in a variable string
3 direct replies — Read more / Contribute
by jayd11
on May 24, 2015 at 01:37

    Hello Monks, need your inputs on the below scenario I am trying to convert sql like operation on perl regular expression I have to compare two variable strings , one string is coming as sql like operator (%) 3 scenarios -

    foo% ( similar in perl ^foo+ ) %foo% ( similar in perl foo +) %f%o% ( no idea on perl)
    I am not able to achieve this in perl , can someone help on this code
    $find1='%'; if ($field2_b ne "") { s/[^$find1]?^/\^/,s/[$find1]?$/+/ for $field2_b + }; if ($field1 =~ /$field2_b/i) { print "fields have pattern matching \n" +;
Threads From Hell #2: How To Search A Very Huge File [SOLVED]
4 direct replies — Read more / Contribute
by karlgoethebier
on May 23, 2015 at 16:04

    Hi all,

    for learning purposes i started to think about how to parse search a very huge file using the multithreading capabilities of Perl.

    As i like trivial examples, i started out with something trivial and created some huge file at first:

    karls-mac-mini:monks karl$ ls -hl very_huge.file -rw-r--r-- 1 karl karl 2,0G 23 Mai 19:38 very_huge.file karls-mac-mini:monks karl$ tail very_huge.file Lorem ipsum kizuaheli Lorem ipsum kizuaheli Lorem ipsum kizuaheli Lorem ipsum kizuaheli Lorem ipsum kizuaheli Lorem ipsum kizuaheli Lorem ipsum kizuaheli Lorem ipsum kizuaheli Lorem ipsum kizuaheli nose cuke karl karls-mac-mini:monks karl$ wc -l very_huge.file 100000001 very_huge.file

    By RTFM i figured out this using MCE::Grep:

    #!/usr/bin/env perl use strict; use warnings; use MCE::Grep; use Data::Dump; use Time::HiRes qw (time); MCE::Grep::init( { max_workers => 4 } ); my $start = time; open( my $fh, '<', 'very_huge.file' ); my @result = mce_grep { /karl/ } $fh; close $fh; printf "Took %.3f seconds\n", time - $start; dd \@result; __END__ karls-mac-mini:monks karl$ ./ Took 29.690 seconds ["nose cuke karl\n"]

    Good old grep performs very much better easily:

    karls-mac-mini:monks karl$ time grep karl very_huge.file nose cuke karl real 0m2.563s user 0m2.176s sys 0m0.309s

    I don't know if this trivial exercise is peinlich parallel, but i'm wondering how to:

    • do this "by hand" (without using MCE::Grep)
    • ...and improve the performance

    Thank you very much for any hint and best regards,


    Edit: Striked out nonsense.

    Ouch! Perhaps more RTFM would have helped:

    PID Prozessname Benutzer % CPU Physikal. Speic Virt. S +peicher 1065 perl karl 12,7 10,3 MB 2, +33 GB 1068 perl karl 83,7 3,9 MB 2, +33 GB 1069 perl karl 84,6 3,9 MB 2, +33 GB 1070 perl karl 83,5 3,9 MB 2, +33 GB 1071 perl karl 84,0 3,9 MB 2, +33 GB

    Edit 2: Renamed the thread


    «The Crux of the Biscuit is the Apostrophe»

Limited idea in perl network programming IO::Socket::INET threads
No replies — Read more | Post response
by Muskovitz
on May 23, 2015 at 10:41

    Hello monks! im here again because i can't really make a messenger in perl i have a very limited amount of networking in perl i was trying to create a messenger in perl where you can select who you want to chat e.g i want to chat John so i just want to click his name and start chatting. So here's my code i push all the filehandles in 1 array which it turns to group chat. But i don't want group chat but i don't know what to do with this filehandles!

    #!/usr/bin/perl use strict; use warnings; use IO::Socket::INET; use threads; use threads::shared; my @clients : shared; @clients=(); my $socket=new IO::Socket::INET( LocalAddr=>'localhost', LocalPort=>7777, Proto=>'tcp', Timeout=>7200, Listen=>7, Reuse=>1 ) || die "$!\n"; while(1){ my $client; $client=$socket->accept; my $peerhost=$client->peerhost; my $peerport=$client->peerport; print "$peerhost:$peerport\n"; my $f_client=fileno $client; push(@clients,$f_client); my $thr=threads->create(\&accept,$client,$peerhost,$f_client); } sub accept{ my ($client1,$peerhost1,$f_client1)=@_; if($client1->connected){ while(<$client1>){ foreach my $fn(@clients){ open(my $fh, ">&=$fn") || die "$!\n"; print $fh "$_"; } } } }
Conditional use of modules
2 direct replies — Read more / Contribute
by tkguifan
on May 23, 2015 at 07:08
    I'm planning to upload my GUI to GitHub but for portability reasons I want to make it depend solely on core perl + Tk and make using other modules conditional. For example the GUI has functions that copy some content to the Windows clipboard, but this is certainly not portable ( it requires an operation system specific module and even the very concept of a clipboard is not portable between operation systems ). What is the prudent way to test whether the clipboard module is present in the system and make the use of the module conditional on this?
    use Win32::Clipboard;
a full-featured control for uploading files and a couple other tidbits
2 direct replies — Read more / Contribute
by Datz_cozee75
on May 23, 2015 at 03:10

    Hello Monks,

    I've been rather ambitious with perl projects lately, porting my html template from a linux laptop to a windows 8.1 laptop with a cygwin installation. I was stunned with how little resistance I encountered, but I do have a couple problems. First, I'd like to address the main topic of this post, which is creating a sensible control for uploading binary content to my site. Let me show you what I have but preface it by saying that I'm without perltidy at the moment (see question 2).

    sub upload { use strict; use warnings; use 5.010; use Net::FTP; use Data::Dumper; my ($rvars, $rftp) = @_; my %vars = %$rvars; # get local files into an array my @filetypes = qw/jpg jpeg png ogv mp4 m4v webm/; my $pattern = join '|', map "($_)", @filetypes; my @matching; opendir my $eh, $vars{"to_vids"} or warn "can't open vids $!\n"; while (defined ($_ = readdir($eh))){ next if m/~$/; next if -d; if ($_ =~ /($pattern)$/i) { push(@matching, $_); } } closedir $eh; # stat local files, create hash #my %stat = map { # lstat($_) or die "Can't lstat $_: $!"; # $_ => { # s => ( -s _ ), # } #} @matching; #my $hashref = \%stat; #print Dumper($hashref); $rftp->cwd("/pages/eh5v.files") or warn "cwd failed in main $!\n"; my $rlist = $rftp->ls(); say "list is @$rlist"; $rftp->binary or warn "binary failed$!\n"; for ( @matching) { #say "matching is @matching"; my $a = file($vars{"to_vids"},$_); my $sa = $a->stringify; #$rftp->put($sa, $_) or warn "put failed $@\n"; } $rftp->ls(); return $rftp; }

    The relevant part of the output is:

    loading vids list is . .. kitchen.jpg kitchen.m4v kitchen.webm stairs.jpg stairs.m4 +v

    What am I trying to do? I want a control to loop through the above files, and first see whether it exists on the remote server. If not, we upload it. If yes, then I'm interested in whether they are either a differing size or creation date. That's what the commented lstat part was to address, but I got errors out of that, because I didn't build the full path. (I think.) If they are different, I want a prompt to overwrite with the default being yes. If they are not different, then I want a prompt to overwrite with the default being no. It would be cool if this could work on a five-second timer. Furthermore, I would like not to create race conditions. And finally, I'd like to have a portion of code to deal with error handling such as time-outs, or directory doesn't exist. The directory, of course "should" exist, but that's one of those words....

    So that's very ambitious, and I'm not completely-wed to any part of the spec if it's ill-advised, but I thought I'd throw the whole thing out there in the original post. If I get it right once, it's eminently re-usable.

    I have 2 other questions that are unrelated to the above. I don't think they deserve their own threads. To the extent that a subthread lasts more than one level, maybe we can rename it appropriately. How do I get CPAN to kickstart?

    $ perl -MCPAN -e shell Set up gcc environment - 3.4.5 (mingw-vista special r3) cpan shell -- CPAN exploration and modules installation (v1.9800) Enter 'h' for help.

    This hangs. I'm running the 64-bit cygwin download that is no more than 2 weeks old on a 64-bit windows 8.1 machine. Do I have cpan and not know it? I don't think so:

    Fred@Psiborg ~/pages2/krov $ sudo cpan -bash: sudo: command not found Fred@Psiborg ~/pages2/krov $ cpan -bash: cpan: command not found Fred@Psiborg ~/pages2/krov $ cpan My :: Module -bash: cpan: command not found Fred@Psiborg ~/pages2/krov $

    Finally, I reached the level of Scribe recently, and I think it would behoove me to have a better brand name. To this end, I'd like to change my username to something cooler and more-identifiable than my current one, which is just an arbitrary 'nym. How do I do that?

CAM::PDF populating form fields
1 direct reply — Read more / Contribute
by PeterPerl2011
on May 22, 2015 at 22:26
    I have code that successfully populates fields in a pdf from a database, using CAM::PDF. However, the text is invisible. That is, when you open the output pdf, the fields appear to be blank. If you click in a field, you see the text that should be there. When you click away, the text disappears again. The text only appears in the field with cursor.

    Anyone else ever see that?

    my $pdf = CAM::PDF->new($file); $pdf->fillFormFields(%form); $pdf->cleanoutput($outfile);

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 chanting in the Monastery: (6)
    As of 2015-05-24 15:59 GMT
    Find Nodes?
      Voting Booth?

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

      Results (474 votes), past polls