Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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
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
1 direct reply — 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 ?


replace all numerics to words in a txt file
3 direct replies — Read more / Contribute
by imhacked
on Sep 22, 2017 at 02:22

    Hi, I am trying to replace all numerics to words in a very large txt file. Example as follows Sentence : I am going to 44 avenue. Result : I am going to forty four avenue. I have written as follows :

    use Lingua::EN::Numbers qw(num2en num2en_ordinal); if(isdigit (\w) s/(\w)/num2en(\w)/g;

    But I get following error :

    Unquoted string "w" may clash with future reserved word at + line 21. syntax error at line 22, near ") s/(\w)/num2en(\w)/g" Execution of aborted due to compilation errors
Perl not able to read file
3 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 22, 2017 at 02:12
    The last line of the following program is not able to read the file Data file = MultiLineData.txt 19760 Austria 7800 Kingsland 124 Petrie Terrace 19762 19764 19765 19767 Austria 7864 Kingsland 1/249 Coronation Drive 19768 19770 Austria 7853 Kingsland Lawrence: 103 Frasers Rd 19771 19775 Austria 7800 Kingsland 127 Edward Street 19777 19779 19780 Austria 7963 Kingsland 133 King Street 19782 19784 19785 19787 19789 19791 Austria 7800 Kingsland Riverside Centre Level 29 123 Eagle Street 19793 19795 19796 19799 67301 67302 67304 Austria 7810 Kingsland Argyle Office Suit 9 20 Argyle Street 67306 67308
    use strict; use warnings; my $dir = 'C:\Scripts'; open(my $fh1, '<', "$dir\\MultiLineData.txt") or die $!; open(my $out1, '>', "$dir\\work.txt") or die $!; open(my $fh2, '<', "$dir\\work.txt") or die $!; while (my $row = <$fh1>) { chomp $row; my $str = $row; $str =~ s/\t/|/g; print $out1 "$str\n"; } while (<$fh2>){chomp $_; print "$_\n"};
Hashing temporal tables in PostgreSQL
1 direct reply — Read more / Contribute
by gtk
on Sep 22, 2017 at 01:23
    Hi All, I am in a process of writing a perl script to hash tables in a schema to track any changes done in table definition level. This is thoroughly for the security purpose and to minimize the unauthorized changes in the DB. So the plan is to generate a Hash/Checksum key for each table and store in a temporary table after any deployment. Then generate the Hash/Checksum key value again before the next deployment and compare the previous Hash/Checksum values. Please let me know a correct way to do this in PostgreSQL. I did the same thing Oracle DB by using DBMS_CRYPTO function and couldn't able to find a way in PostgreSQL. So please suggest me a way to handle this hashing tables method and relevant functions/utilities? Thanks.

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
    and all is quiet...

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

      Results (274 votes). Check out past polls.