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
Most direct way of loading XS?
3 direct replies — Read more / Contribute
by YenForYang
on Feb 17, 2018 at 20:59

    Recently I've been looking into what XSLoader and DynaLoader and I've been trying to figure out what they do behind the scenes so that maybe I can do (what they do) ("low-level") if I so wish (for whatever reason). It seems to me that XSLoader.pm just uses DynaLoader--it's a convenient module but using it to load XS seems like just an extra step. Well I've looked at DynaLoader as well, and I'm lost on how it does what it does. It implements functions like dl_load_file, dl_install_xsub, and dl_find_symbol but I can't seem to find any definitions. So I'm guessing they are defined in XS or something...but if the subroutines for loading XS are defined in XS, how does DynaLoader manage to do anything?

Graph.pm: How do I represent one-way dependency?
1 direct reply — Read more / Contribute
by jkeenan1
on Feb 17, 2018 at 19:45

    I am attempting to use the Graph module from CPAN for the first time. I am having trouble understanding how the module implements the concept of a "directed graph".

    Suppose I have 3 nodes, "Jolt", "Lord", and "Tornado". I want to indicate that "Tornado" depends on each of "Jolt" and "Lord". Based on the Graph distribution's t/06_new.t and t/18_add_edge.t, I believe I can say that with the following program:

    $ cat graph.t #!/usr/bin/env perl use strict; use warnings; use Graph; use Test::More qw( no_plan ); my @vertices = qw( Jolt Lord Tornado ); my $g = Graph->new(vertices => [ @vertices ]); ok(defined $g, "Constructor returned defined value"); isa_ok($g, 'Graph'); for my $v (@vertices) { ok($g->has_vertex($v), "vertex $v"); } my @edges = ( [ 'Tornado' => 'Jolt' ], [ 'Tornado' => 'Lord' ], ); for my $e (@edges) { ok($g->add_edge(@{$e}), sprintf("Add edge %-12s -> %s", @{$e})); }
    When I run this, I get this output:
    $ prove -v graph.t graph.t .. ok 1 - Constructor returned defined value ok 2 - An object of class 'Graph' isa 'Graph' ok 3 - vertex Jolt ok 4 - vertex Lord ok 5 - vertex Tornado ok 6 - Add edge Tornado -> Jolt ok 7 - Add edge Tornado -> Lord 1..7 ok All tests successful. Files=1, Tests=7, 0 wallclock secs ( 0.02 usr 0.00 sys + 0.11 cusr + 0.00 csys = 0.13 CPU) Result: PASS
    So far so good. But to me "depends on" means that I should not be able to add an edge from "Jolt" to "Tornado" or from "Lord" to "Tornado" because I've already established the other direction for those edges. So my expectation is that, I when I add the following unit test:
    ok(! $g->add_edge( 'Lord' => 'Tornado '), "I expect that I cannot add Lord -> Tornado edge");
    ... the test will PASS because it is phrased in the negative. Instead, the test FAILs:
    $ prove -v graph.t graph.t .. ok 1 - Constructor returned defined value ok 2 - An object of class 'Graph' isa 'Graph' ok 3 - vertex Jolt ok 4 - vertex Lord ok 5 - vertex Tornado ok 6 - Add edge Tornado -> Jolt ok 7 - Add edge Tornado -> Lord not ok 8 - I expect that I cannot add Lord -> Tornado edge # Failed test 'I expect that I cannot add Lord -> Tornado edge' # at graph.t line 23. 1..8 # Looks like you failed 1 test of 8. Dubious, test returned 1 (wstat 256, 0x100) Failed 1/8 subtests Test Summary Report ------------------- graph.t (Wstat: 256 Tests: 8 Failed: 1) Failed test: 8 Non-zero exit status: 1 Files=1, Tests=8, 0 wallclock secs ( 0.01 usr 0.01 sys + 0.11 cusr + 0.00 csys = 0.13 CPU) Result: FAIL

    So, what am I not grokking about Graph and directed graphs? Is it possible to implement what I want with Graph, or is some other module better for this?

    Thank you very much.

    Jim Keenan
Redirecting Output to shell command from within perl
4 direct replies — Read more / Contribute
by dracut
on Feb 16, 2018 at 19:32
    Hey guys, not sure if this has been answered here before, but I was looking to feed less a string stored within a variable $output.
    Essentially I'm trying to do the following from within the script:


    Any help would be greatly appreciated!
Writing to File based on condition
4 direct replies — Read more / Contribute
by cbtshare
on Feb 16, 2018 at 16:57

    Hello All, I have the script below that is suppose to run against a file with a list of ip addresses, check if they are up or not .If they are up just print, if they are not write to a file after it determines if its empty or not, but I also want that file to have no duplicates, so I have the following, seems like over kill to do a simple task.It runs, but when I get to if the host is not up, that section doesn't even run (I know this because I put dead ip addresses in the list.Can you please assist

    #!/usr/bin/perl use warnings; use strict; my $awsGone = "/ansible/awsGone"; my $awsLists = "/ansible/awsLists"; my @ips; open(FILE, '<', $awsLists) || die("Could not open file, $!"); @ips = <FILE>; close FILE; foreach my $addy(@ips) { chomp($addy); #Test if up my $retreval=system qq{nc -w 1 $addy 22 > /dev/null 2>&1}; if($retreval==0) { print "This up -> $addy\n"; } else { ##check if the file is empty, dont bother searching for +duplicates if(-z "$awsGone") { print "Host not up\n"; open(WRITE,'+>>',"$awsGone") || die("canot open $awsGone,$ +!"); print WRITE "$addy\n"; close WRITE; #remove dead ip from file system qq{perl -p -i -e "/$addy/" $awsLists}; } else { ##ip is dead, so open file for writing, then check if d +ead ip is already there open(WR,'+>>',"$awsGone") || die("canot open $awsGone,$!") +; while(my $line = <WR>) { if($line =~ /$addy/) { print "already exists\n"; } else { ##Append dead ip to the file print "Host not up now\n"; print WR "$addy\n"; close WR; system qq{perl -p -i -e "/$addy/" $awsLists}; } } } } }
    My test file looks like below, all are good except the 3rd and 4th
    ip-10-1-0-152.us-west-2.compute.internal ip-10-1-0-239.us-west-2.compute.internal ip-10-55-55-55.us-west-2.compute.internal ip-10-122-122-122.us-west-2.compute.internal ip-10-1-1-143.us-west-2.compute.internal ip-10-1-1-149.us-west-2.compute.internal ip-10-1-1-150.us-west-2.compute.internal ip-10-1-1-167.us-west-2.compute.internal
    my results are
    This up -> ip-10-1-0-152.us-west-2.compute.internal This up -> ip-10-1-0-239.us-west-2.compute.internal This up -> ip-10-1-1-143.us-west-2.compute.internal This up -> ip-10-1-1-149.us-west-2.compute.internal This up -> ip-10-1-1-150.us-west-2.compute.internal This up -> ip-10-1-1-167.us-west-2.compute.internal
Convert string to variable
4 direct replies — Read more / Contribute
by ShermW0829
on Feb 16, 2018 at 15:27

    Name: Sherman 71 years old retired and creating my own poker visits database

    Platform: HP Compaq 6710b

    Operating System: Ubuntu 17.10

    PERL Version: 5.26

    postgresql Version: 9.6

    Problem: Need to assign a string to act as a variable

    I am building a front end for postgresql entries. I have fourteen entries that I need to query the user and set the user's value into a variable. I am using IO::Prompt.

    If I straight-line the code everything works. e.g:

    my ($date_in, $date_out); $date_in - prompt("Start Date: "); $date_in =~ s/^\s+|\s+$//g; $date_out = prompt("$End Date: "); $date_out =~ s/^\s+|\s+$//g;

    And 12 more user inputs to get along with the no space check equals 24 more lines of code. Lots of code so I tried the following:

    my ($k, $date_in, $date_out); my %var_list = ('date_in'=>'Start Date', 'date_out'=>'End Date'); foreach $k (keys(%var_list)) { ## $k prints date_out and then date_in print( "\$k: \"$k\"\n" ); ## $var_list prints End Date and then Start Date print( "\$var_list{k}: \"$var_list{$k}\"\n" ); ## Below is where I want to go: ## $k = prompt($var_list{k}); ## and have $date_out = user's entry ## ## Now how do I assign a beginning $ ## to change date_out to $date_out? ## The below does not work ## ${$k} = prompt(${$var_list{k}}); ## ## I've tried $$k, $($k), and ${$k} ## An example error is the following: ## Can't use string ("date_out") as a SCALAR ## ref while "strict refs" in use at ## ./build_sql_entries line 25 }

    Thank you;


Appending downlad file LWP
1 direct reply — Read more / Contribute
by Anonymous Monk
on Feb 16, 2018 at 13:52


    I am trying to improve some code. Basically, I want to build a downloader with progress bar. I know how to download file, how to build a progress bar (for example in Tk). What I cannot solve is appending the portion of file I have downloaded to the main (final) file. Here it is what I got (stripped of the GUI part. The code is based on a solution I found on the web.

    use strict; use warnings; use LWP::Simple; use LWP::UserAgent; my $url='www.myurl.com'; my $ttlDown = 0; my $resp = LWP::UserAgent->new()->get($url, ':content_cb' => sub { my ($data, $response) = @_; my $size = $response->content_length; $ttlDown += length $data; printf("%7.1f KB of %7.1f (%5.1f%%)$/", $ttlDown / 1024.0, $size / 1024.0, $ttlDown * 100.0 / $size ); #Here I need to append the bit of file downloaded, but I am down +loaded the entire file over and over... my $file = 'myfile.exe'; getstore($url, $file); });
Compilation failed in require, but how to get the actual compilation error?
1 direct reply — Read more / Contribute
by Anonymous Monk
on Feb 16, 2018 at 12:13

    Hi everyone, I have a script called switchscan.pl which is turned into an executable called switchscan through the use of Par Packer. When I run the switchscan, it tries to load the module SwitchScan::Service::local::mlnx, but I end up with this error:

    Attempt to reload SwitchScan/Service/local/mlnx.pm aborted (#1) (F) You tried to load a file with use or require that failed to compile once already. Perl will not try to compile this file agai +n unless you delete its entry from %INC. See "require" in perlfunc +and "%INC" in perlvar. Compilation failed in require at script/switchscan.pl line 42 (#2) (F) Perl could not compile a file specified in a require statement +. Perl uses this generic message when none of the errors that it encountered were severe enough to halt compilation immediately. BEGIN failed--compilation aborted at script/switchscan.pl line 42 (#3) (F) An untrapped exception was raised while executing a BEGIN subroutine. Compilation stops immediately and the interpreter is exited. Uncaught exception from user code: Attempt to reload SwitchScan/Service/local/mlnx.pm aborted. Compilation failed in require at script/switchscan.pl line 42. BEGIN failed--compilation aborted at script/switchscan.pl line 42.

    How do I get the actual error that caused the compilation failure? When I run perl -c on mlnx.pm before packing everything with Par Packer, I get "syntax OK". Something in the packing process is causing the failure, but I'm at a loss for how to further troubleshoot.

    Much appreciated.

including variables
6 direct replies — Read more / Contribute
by LloydRice
on Feb 16, 2018 at 11:32

    I have a short bit of Perl variable definitions that I would like to use in two different scripts. The simple plan is that I would not need to maintain 2 copies of that fragment. I have tried do, exec, use, module, a few more things. It all seems designed to defeat my simple goal by imposing all of the module structure. As I read the new Camel book, "do" should do what I want. But the variables do not get into the calling script. What am I missing?

HASH Hierarchy
3 direct replies — Read more / Contribute
by dirtdog
on Feb 16, 2018 at 10:40

    Hi Monks, I've got a working snippet of code that will take parameters and stuff them into a hash to be used later in the program to only keep the highest ranked value only (0 is top ranked) if it exists.

    #!/usr/bin/env perl use strict; my @hierarchy; my %hierarchy; my $order =0; while ($#ARGV >= 0) { push @hierarchy,shift; } for (@hierarchy) { $hierarchy{$_} = $order; $order++; } while( my( $key, $value ) = each %hierarchy ){ print "$key: $value\n"; }

    The code appears to work, but I thought there might be a better way to do it so thought I'd check with the Monks.

    Much appreciated!

why does par packer cause incorrect Perl-Tk server() output?
5 direct replies — Read more / Contribute
by perltux
on Feb 16, 2018 at 05:38
    Given the following script:

    use strict; use warnings; use Tk; my $mw=MainWindow->new(); print STDOUT "PerlTk server: [". $mw->server() ."]\n";

    If I run the above script on Windows 10 using StrawberryPerl I get the following output which is as expected:

    PerlTk server: [Windows 10.0 10586 Win32]

    but if I create an exe of the above script with Par::Packer on the same system I get the following wrong output when running the exe:

    PerlTk server: [Windows 6.2 9200 Win32]

    Why does Par::Packer change the output of the Tk 'server()' command making it incorrect and what do I have to do to get the correct output when using an exe created by Par::Packer?

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.