Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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
When modules install in perl5
4 direct replies — Read more / Contribute
by cristofayre
on Sep 25, 2017 at 08:00

    My shared server has the usual "!#/usr/bin/perl" for use by everyone, but personal installations appear to go into "perl/usr/lib/perl5" folder.

    So if my scripts access the former, all is well. But to access the latter ...??? Have I got to change all my scripts to the new path of "!# perl/usr/lib/perl5" or is there a way to 'force' the new path into @inc. How would you do it if some "use xxx" are in /usr/bin/perl, and some in the second folder?

    Did my last host use a "symlink" for this, and if so, where did he put it.

    Finally, if the "use" entry could not be found, would this generate a "suexec violation" error? A script using "File::Find::Rule", permission 755 designed to update all the file permissions came back with the above for a 500 error. I asked host, and their response: "Please set all your perl files to 755" (In otherwords, they had no idea!)

    This is the script:

    #!/usr/bin/perl print "content-type: text/html\n\n"; # use CGI::Carp qw( fatalsToBrowser ); use File::Find::Rule; my @files = File::Find::Rule->file()->name('*.pl')->in('/home/cristofa +/public_html'); # set ->in('.') to start from current directory for ($x=0; $x<@files; $x++){ chmod (0755, $files[$x]); print "$files[$x]&lt;br&gt;"; } print "All done";

    # CARP is commented out because - whilst CGI is installed - it doesn't specifically list CGI::CARP. I installed the latter ... which comes back to the initial "perl5" path query! Script works on my Windows / Strawberry perl version.

    And yes, I know you CAN use a foreach / while loop ... but I still find that a bit 'symbolic' and prefer to 'see' what's happening each loop.

Looping trough Array Key/Value Pairs
3 direct replies — Read more / Contribute
by maikelnight
on Sep 25, 2017 at 06:45

    Dear Monks, i am new to perl...I have an array which Dumps to this:

    $VAR1 = { '_shards' => { 'skipped' => 0, 'successful' => 5, 'total' => 5, 'failed' => 0 }, 'hits' => { 'hits' => [ { '_id' => 'AV6SrwuTv7sBjjRqMiW1', '_source' => { 'request' => '/inde +x.php', 'clientip' => '192. +168.1.1' }, '_type' => 'nginx', '_index' => 'nginx-2017.09.18', '_score' => '4.238926' }, { '_id' => 'AV6UL-DOv7sBjjRqMidb', '_source' => { 'clientip' => '192. +168.1.1', 'request' => '/' }, '_score' => '4.189655', '_type' => 'nginx', '_index' => 'nginx-2017.09.18' } ], 'total' => 2, 'max_score' => '4.238926' }, 'took' => 0, 'timed_out' => undef };

    I try to get the key/values from '_source' but i dont know how. I can dump for example with: "print Dumper $_->{'hits'}{'hits'}->[0]->{'_source'};" and foreach, and get the pair from [0] and i can alter [0] to 1 and get the other pair.

    foreach $_(@testarray) { print Dumper $_->{'hits'}{'hits'}->[0]->{'_source'}; }

    But how can i loop through to get all the values? I tried to loop with foreach and a counter but it didnt work, it always gives [0] (indeed i might make a mistake). May i ask one to get me some help how to? Thanks a lot.

Why is @flds not imported?
3 direct replies — Read more / Contribute
by perl-diddler
on Sep 24, 2017 at 17:38
    I was getting an error in one of my progs and distilled the problem. I only tested it on 5.16 and 5.20, but I don't remember any changes in more recent perls that might indicate it's fixed.
    # # note: may need to install "mem" ("cpan -i mem") # use strict; use warnings; ###################################################################### +########## { package Fields; use strict; use warnings; use mem; our (@flds, @EXPORT); @EXPORT=qw(@flds); use Exporter 'import'; } ###################################################################### +########## package main; use strict; use warnings; use Fields; my $nfld = scalar @flds;

    I get error:

    > perl t02-array.t Global symbol "@flds" requires explicit package name at t02-array.t li +ne 19. Execution of t02-array.t aborted due to compilation errors.
    If I put qw(@flds) after the use Fields, I get:
    "@flds" is not exported by the Fields module
    I think I'm missing something obvious.... :-(.


Dancer::Plugin::Database::Core::Handle quick_select with where or condition
1 direct reply — Read more / Contribute
by RamiD
on Sep 24, 2017 at 13:26

    I am using perl Dancer::Plugin::Database::Core::Handle quick_select ,

    in the where cluser , by default , every comma between the condition is like and

    database->quick_select($table,   { foo => 'Bar', bar => 'Baz' });

    Here the conditions is with and operator , foo should be qual to Bar and bar should be Baz

    what about Or operand , how can I do quick_select with where Or operator

    thanks Rami D.
PPI replacing/updating a stub
3 direct replies — Read more / Contribute
by clueless newbie
on Sep 24, 2017 at 11:41

    How to replace a (sub's) stub using PPI?

    I'm playing with PPI and the problem of fleshing out a stub has me baffled. The following snippet illustrates my problem.

    #!/usr/bin/env perl use if (-d 'C:/Users/clueless_newbie'),lib=>'C:/Users/clueless_newbie/ +GOOGLE~1/code/lib'; use if (-d 'C:/Users/clueless_newbie'),lib=>'C:/Users/clueless_newbie/ +code/Perl-5/devlib'; # $ENV{DBG} -> compile time; $ENV{DEBUG} -> run time. use if ($ENV{DBG} || $ENV{DEBUG}),"Devel::UnComment","#[=]#","Keep"; use Data::Dumper; use PPI; use PPI::Dumper; use strict; use warnings; use 5.10.0; { # INTERNALS }; # INTERNALS my $raw=<<'__RAW__'; package FeeFi; sub Fee { print "Fee\n"; } sub Fi { print "Fi\n"; } -1; __RAW__ my %sub_h; { # Save the subs; replacing them with placeholders # Create the PPI document my $document=PPI::Document->new(\$raw) or die "oops!"; $document->save('before'); for my $sub (@{$document->find('PPI::Statement::Sub') || []}) { unless ($sub->forward) { #say $sub->name; # save the sub and its content $sub_h{$sub->name}{content}=$sub->content; # Replace the sub's block as a stub by removing its childr +en my @elements=$sub->block->children; for (my $i=0; $i < @elements; $i++) { $elements[$i]->remove; }; }; }; # Save the stubbed out "main/package" under the key ''; $sub_h{''}{content}=$document->content; }; #=# DEBUG [ sub_h=>\%sub_h ]; # Completing the round trip { # Create the stubbed out main my $document=PPI::Document->new(\$sub_h{''}{content}) or die "oops creating ''!"; #=# DEBUG '',PPI::Dumper->new($document,whitespace=>0)->string; # Find and flesh out the stubs for my $stub (@{$document->find('PPI::Statement::Sub') || []}) { unless ($stub->forward) { my $name=$stub->name; #=# TRACE $name; # Flesh out this stub my $sub=PPI::Document->new(\$sub_h{$name}{content})->find_ +first('PPI::Statement::Sub'); #=# TRACE '',PPI::Dumper->new($sub,whitespace=>0)->string; # So ow do I flesh out the stub from $sub???? $stub->insert_after($sub) # <=== Doesn't do it! or warn "Can't insert_after!"; #=# DEBUG '',PPI::Dumper->new($document,whitespace=>0)->st +ring; }; }; #=# DEBUG '',PPI::Dumper->new($document,whitespace=>0)->string; $document->save('after'); # <=== "after" should be prog +rammatically equal to "before" }; exit;
How to do popcount (aka Hamming weight) in Perl
5 direct replies — Read more / Contribute
by eyepopslikeamosquito
on Sep 24, 2017 at 06:23

    In More Betterer Game of Life, I needed a popcount (aka Hamming weight) function to sum the one bits in a 64-bit value.

    I started with the basic popcount1 below, scraped with little thought from the Hamming_weight wikipedia page.

    I'd like to improve that, hence this node.

    use strict; use warnings; use Benchmark qw(timethese); sub popcount1 { my $x = shift; my $count; for ($count = 0; $x; ++$count) { $x &= $x - 1 } return $count; } sub popcount2 { return sprintf('%b', shift) =~ tr/1//; } sub popcount3 { return unpack('%32b*', pack('Q', shift)); } my $start = 2**32 - 42; my $end = $start + 1000000; print "sanity test for correctness\n"; for my $i (0 .. 256, $start .. $end) { my $one = popcount1($i); my $two = popcount2($i); my $three = popcount3($i); # print "$i: $one $two $three\n"; $one == $two or die; $one == $three or die; } timethese 50, { One => sub { popcount1($_) for $start .. $end }, Two => sub { popcount2($_) for $start .. $end }, Three => sub { popcount3($_) for $start .. $end }, };

    Running the above program on my machine produced:

    sanity test for correctness Benchmark: timing 50 iterations of One, Three, Two... One: 29 wallclock secs (28.41 usr + 0.00 sys = 28.41 CPU) @ 1.76/ +s (n=50) Three: 10 wallclock secs (10.00 usr + 0.00 sys = 10.00 CPU) @ 5.00/ +s (n=50) Two: 10 wallclock secs (10.03 usr + 0.00 sys = 10.03 CPU) @ 4.98/ +s (n=50)

    Improvements welcome.


Need Help with Perl Code
5 direct replies — Read more / Contribute
by freedomxcruiser
on Sep 23, 2017 at 19:24

    here's the question. If any one could help me out that would be great.

    2. Assignment 7 – The Currency Converter in Chapter 2, change the currency conversion program so that it asks for an exchange rate and three prices to convert.

    Begin this exercise with the starter file in the Assignment zip folder.

    Downloading Perl: Be sure to DOWNLOAD the latest version of PERL for your Operating System from the following link: Let your instructor know if you have any questions about installation. The file should be installed on the C: drive to a folder called Perl64 (this folder will be created automatically.)

    Store the Variables
    Return the Results
    Ensure Results Are Accurate to Two Decimal Places

    I need the code created and it needs to store the variables, return the results, and ensure results are accurate to two decimal places. Thanks for all the help!


Help with exercise
2 direct replies — Read more / Contribute
by codeKnight
on Sep 22, 2017 at 19:46
    Hi guys, I am teaching myself perl and I'm working on an exercise that I'm particularly stumped on. The task is to write a perl script that accepts a valid directory as an argument. Using the argument passed, change into the given directory. Once inside, create two more directories. I've written this exact same script using BASH before and it worked perfectly. I'm just trying to figure out where I'm going wrong because as of right now, the script does nothing. Here's what I have:
    #!/usr/bin/perl #Script to create required directories in user provided location argum +ent. my $Dir = $ARGV[0]; if(! -e "$Dir") { print "Please try again with a valid directory.\n"; exit 1; } elsif(! -d "$Dir") { print "Please try again with a valid directory.\n"; exit 1; } elsif(($#ARGV+1) < 1) { print "Please try again with a valid directory.\n"; exit 1; } #Change to user selected location chdir($Dir);
Win32 Network Adapter module naming
3 direct replies — Read more / Contribute
by VinsWorldcom
on Sep 22, 2017 at 09:25

    A while back I needed a Win32 module for getting network interface / adapter information much like IO::Interface or Net::Interface or Net::Libdnet .. but for Windows (obviously). Also, I know of Win32::IPConfig and Win32::IPConfig::Adapter which use the registry, but don't have all the functionality I needed. Finding nothing that suited at the time, I started to write one myself using XS and hitting the GetAdaptersAddresses() API and parsing the IP_ADAPTER_ADDRESSES structure, but alas my XS skills suck and I ended up writing a Perl interface around some 'wmic', 'netsh' and other Windows command line calls. Hey, it worked.

    I thought about CPAN upload for a long while (years) and now I probably should, but what to name it? Originally, 'Win32::GetAdapterAddresses' would have been a good name, but I don't do the XS API integration so didn't want to misrepresent the functionality. It's currently called 'Win32::Interface' - which made sense since at the time, IO::Interface was mainly the functionality I was trying to duplicate. But now not so sure. How about ...

    • Win32::Interface - descriptive (for me), but thinking of others, I'm now not so sure. Also, I see Win32::API::Interface which is totally unrelated and I could cause confusion.
    • Win32::Adapter - maybe?
    • Win32::Network::Adapter - getting un-useful-ly long just to be overly descriptive
    • Win32::Network::Interface - same as above
    • IO::Interface::Win32 - I'm not actually sub-classing IO::Interface, so probably not a good idea
    • Net::Interface::Win32 - same as above
    • Win32::IO::Interface - just iterating names now ...
    • Win32::IO::Adapter - and again ...
    • Win32::Net::Interface - again ...
    • Win32::Net::Adapter - ...

    Mainly, should it live under IO::, Net:: or Win32::, and then what name under the top level namespace? Suggestions? Maybe a Perlmonks Poll?!?

perlcall for dummies
2 direct replies — Read more / Contribute
by frazap
on Sep 22, 2017 at 03:10
    I have the following files for a embryonic keyboard hook on windows


    package Kbh; our $VERSION = '0.01'; require XSLoader; XSLoader::load('Kbh', $VERSION); sub process_key { print "process_key in perl\n"; } 1;
    use ExtUtils::MakeMaker; WriteMakefile ( NAME => 'Kbh', VERSION => '0.01', OBJECT => 'hook.o Kbh.o', );
    LRESULT CALLBACK HookCallback(int nCode, WPARAM wParam, LPARAM lParam) +; void processKey(); void register_hook(); void unregister_hook(); void MsgLoop();
    #include <windows.h> #include <WinAble.h> #include "stdio.h" #include "hook.h" HHOOK hook; LRESULT CALLBACK HookCallback( int nCode, WPARAM wParam, LPARAM lParam + ) { processKey(); return CallNextHookEx( hook, nCode, wParam, lParam ); } void processKey() { printf("processKey in C\n"); } void MsgLoop() { MSG message; while ( GetMessage( &message, NULL, 0, 0 ) ) { TranslateMessage(&message); DispatchMessage(&message); } } void register_hook() { HMODULE hMod = (HMODULE) GetModuleHandle(NULL); hook = SetWindowsHookEx( WH_KEYBOARD_LL, HookCallback, hMod, 0 ); } void unregister_hook() { UnhookWindowsHookEx(hook); }
    and Kbh.xs
    #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" #include "hook.h" MODULE = Kbh PACKAGE = Kbh PROTOTYPES: DISABLE void MsgLoop() void register_hook() void unregister_hook() void processKey() INIT: int count; PPCODE: dSP; PUSHMARK(SP); count= call_pv("Kbh::process_key", G_DISCARD|G_NOARGS); if (count != 0) croak("Big trouble\n");
    When I run
    Perl dmake

    the things compile.

    When I run from the main directory(use ctrl+c to quit)
    use lib qw(./lib ./blib/arch/auto/Kbh); use Kbh; Kbh::register_hook(); Kbh::MsgLoop; Kbh::unregister_hook();
    I see that the hook is installed, I get two messages from processKey when I hit a key, but I don't have msg "process_key from perl"

    What am I missing ?



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!
  • 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?

    What's my password?
    Create A New User
    [holli]: Lidl only sells plastic
    [Corion]: holli: Oooh, a twister top - so yes, that's a worse state of mind than it sounded ;)
    [holli]: and since I outed myself anyway as a horrible person, to top it off, the bottle contains beer. alcohol free beer
    [Discipulus]: nowaday such beers have also a good taste
    [Corion]: holli: Heh - if you consider alcohol free beer as a not-so-sweet lemonade, you're not that bad off ;)
    [holli]: actually, that's exactly how i look at it.
    [Discipulus]: leaving alcool is forever. well done bro'

    How do I use this? | Other CB clients
    Other Users?
    Others romping around the Monastery: (15)
    As of 2017-09-25 12:59 GMT
    Find Nodes?
      Voting Booth?
      During the recent solar eclipse, I:

      Results (280 votes). Check out past polls.