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
About personal function
3 direct replies — Read more / Contribute
by dideod.yang
on Jul 19, 2018 at 00:32
    Hi monks. I want to achieve using personal function with many arrays. Below script, I show you sample. According script, only print A... I want to print all of values(A B C) in @x. How can I achieve my personal function.
    my (@x,@y); @x =( "A" "B" "C"); @y =( "C" "D" "F"); &test(@x,@y): sub &test{ @test = @_[0]; print "@test\n"; }
Spreadsheet::read how to get error?
1 direct reply — Read more / Contribute
by gsd4me
on Jul 18, 2018 at 17:32


    I have a program that writes some data into a spreadsheet, which I want to then analyse again to produce some HTML output. The latter part works in testing but putting the whole lot together has raised an interesting problemette. Code replicated below. My debugging is showing that $gOutWorkbook has a value of "undef" upon return from ReadData, and I have no means of knowing why the workbook is not being (re-)opened to be read, when I have populated it with data previously (not shown here)

    So: can I find out the reason *why* the workbook is not being opened properly? (ie some error value from somewhere) I have even put a 10 second delay before I attempt the open, to allow the OS to 'settle down' after closing the file, post writing to it but that doesn't help at all All other variables have relevant and correct values associated with them at the crucial point in the software. Previous ReadData calls work in other parts of the software suite, so it is only this section that is letting me down.

    # Re-open as a read only # Read in the workbook and all its data $gOutWorkbook = ReadData ($lOutputFileName); $gOutWorksheet = $gOutWorkbook->[$gOutWorkbook->[0]{sheet}{"my +Sheet"}];
Abuse of "or next" in expressions and "next" that returns value
4 direct replies — Read more / Contribute
by vr
on Jul 18, 2018 at 15:28

    Today I wrote a script, in which I preferred some logic expressed as 2nd fragment rather than the 1st:

    for ( $x .. $y ) { # some loop # ... skipped ... # fragment #1: next unless exists $gs_val-> { HT }; my $ht = $doc-> getValue( $gs_val-> { HT }); next unless exists $ht-> { Default }; my $df = $doc-> getValue( $ht-> { Default }); next unless exists $df-> { TransferFunction }; my $tf = $doc-> getValue( $df-> { TransferFunction }); next unless $tf eq 'Default; # ... skipped ... # fragment #2: next unless $doc-> getValue( $doc-> getValue( $doc-> getValue( $gs_val-> { HT } || next ) -> { Default } || next ) -> { TransferFunction } || next ) eq 'Default'; # ... skipped ... }

    As you see, I tried to improve the #1 with a few blank lines, but, to me, the #2 is more readable -- now, and I hope it will remain so in a year, when I have to try hard to remember what it all was about. Perhaps not everyone will agree.

    However, while experimenting and testing to see if such constructs are OK, I was surprised to find that Perl prefers even more unexpected form:

    >perl -we "for(\0,0){print${$_||next}}" 0 >perl -MO=Deparse -we "for(\0,0){print${$_||next}}" BEGIN { $^W = 1; } foreach $_ (\0, 0) { print ${next unless $_;}; } -e syntax OK >perl -we "for(\0,0){print${next unless $_}}" 0 >

    Looks like if "or next" is part of block that is supposed to return value, then Perl replaces it with "next unless" syntax. What's totally unexpected is that this "next unless" thing is actually valid and does return value.

    I can only guess that everything works the other way, in reality: "next unless" is optimized to "or next", therefore it returns value, and that for some strange reason B::Deparse shows "||next" as "next unless". That is only way this can be sane... Or is it not so? :)

SFTP for Perl on CygWin
2 direct replies — Read more / Contribute
by pcrowley203
on Jul 18, 2018 at 15:20

    I am running PERL 5.26.2 on CygWIN on Windows 10. I need to execute an sftp from Perl. The base installation of perl doesn't seem to include sftp, so I downloaded and tried to install Net::SFTP. This seems to require Net::SSH2, which I also downloaded and tried to install. That seems to require crypt.h. In attempt to get crypt.h into place, I downloaded and tried to install gcrypt-0.3. Surprisingly, that too requires (and does not include) crypt.h. So I downloaded and tried to install Crypt-GCrypt-1.26. That seems to require the library 'gcrypt'. So I downloaded and tried to install libgcrypt-1.8.3. That requires libgptg-error-1.9, which I downloaded and tried to install. That will not compile because the compiler does not like a long series of lines all of the form: { , "GPG_ERR_SOMETHING"}

    It doesn't seem like this should be so hard. Does anyone have any advice for me?

Histogram Creation
3 direct replies — Read more / Contribute
by Galahad
on Jul 18, 2018 at 11:31

    I have an array of 100 floating point values. I rounded the values to the tenths place in order to create more matches on my histogram. I was wondering how to get these values in an array and put them into a histogram. I have previously checked other posts on PerlMonks, but I end up with errors in my code. I am relatively new to programming in general and I might lack certain programming etiquette or syntax.

    use strict; use warnings; use Data::Dumper; use 5.010; use GD::Graph::histogram; use YAML; use CGI ':standard'; sub main { my $input = 'distance.txt'; unless(open(INPUT, $input)) { die "\nCannot open input\n"; } my @data; while(my $line = <INPUT>) { chomp $line; my @rounded = sprintf ("%.1f\n", $line); push @data, @rounded; my ( $filename, @data ) = @_; my $graph = new GD::Graph::histogram(400,600); $graph->set( y_label => 'Count', x_label => 'Distances', title => 'Histogram', x_labels_vertical => 1, bar_spacing => 0, shadow_depth => 1, shadowclr => 'dred', transparent => 0, ) or warn $graph->error; my $image = $graph->plot(\@data) or die $graph->error; open( IMG, '>' . $filename ) or die $!; binmode IMG; print IMG $image->png; } } main();

    These are the error messages I have been receiving.

    Subroutine main::Dump redefined at /System/Library/Perl/5.18/ line 308. Use of uninitialized value $min in subtraction (-) at /Library/Perl/5.18/GD/Graph/ line 110, line 1. Use of uninitialized value $max in subtraction (-) at /Library/Perl/5.18/GD/Graph/ line 110, line 1. Use of uninitialized value $max in numeric le (<=) at /Library/Perl/5.18/GD/Graph/ line 118, line 1. Use of uninitialized value $upper in numeric le (<=) at /Library/Perl/5.18/GD/Graph/ line 118, line 1. Use of uninitialized value $lower in addition (+) at /Library/Perl/5.18/GD/Graph/ line 119, line 1. Use of uninitialized value $max in numeric le (<=) at /Library/Perl/5.18/GD/Graph/ line 122, line 1. Use of uninitialized value in string eq at /Library/Perl/5.18/GD/Graph/ line 42, line 1. Use of uninitialized value in subtraction (-) at /Library/Perl/5.18/GD/Graph/ line 59, line 1. Use of uninitialized value in addition (+) at /Library/Perl/5.18/GD/Graph/ line 59, line 1. Use of uninitialized value $filename in concatenation (.) or string at /Users/Joshua/eclipse-workspace/PlottingPoints/Histogram line 40, line 1. No such file or directory at /Users/Joshua/eclipse-workspace/PlottingPoints/Histogram line 40, line 1.

sorting and merging in perl
2 direct replies — Read more / Contribute
by Sekhar Reddy
on Jul 18, 2018 at 10:41

    Hello Monks,


    Can any one help me on this, How this can be done in perl

    Thank you very much in advance

    I have 4 different Scenarios, I have listed down, and i have also written how my hash should store

    STRUCTURE OF MY DATA below(with Header, last two fields are date fields in yyyymmdd format):





    For the above content(A1), i want to store in hash like this==>A1,B1 of MIN ACTDATE:B1 of MAX DEACTDATE,MIN ACTDATE,MAX DEACTDATE

    For the above example, ==>7900724666,200906888:200906888,20180406,20180720




    For the above content(A1), i want to store in hash like this==>7900724677,200906871:200906873,20180101,20180420





    For the above content(A1), i want to store in hash like this==>7900724688,200906881:200906883,20180101,20180620





    For the above content(A1), i want to store in hash like this==>7900724699,200906891:NULL,20180101,NULL

Tk question: Dynamically disable radiobutton choices
1 direct reply — Read more / Contribute
by chafelix
on Jul 18, 2018 at 08:32

    I am creating a dialog for comparing two files. For matching purposes, the user needs to tell the program how to handle fields (for instance excel columns). Thus, the interface needs to a) specify that column i in file A corresponds to column j in file B and b) whether these matching columns are First name, last name or neither. This is important because an exact match will be performed for last name, but a first digit match will be performed on first name, e.g. 'Tim' vs. 'Timothy' should be a match. So I am adding a radiobutton for each column with the choices 'First, last and no name'. The trick is that once there is only one 'First name' and 'last name' column, so once the user has specified that this is a first name, this option should not be available to other columns.

    Apart from this, which I am not sure how to do there seem to be 2 more issues with the code below: First, the Radiobutton part seems to give a strange message Second, the Browseentry appears to be filled in the box instead of the expanding list

    use Tk; use Tk::BrowseEntry; my $top=MainWindow->new(); $top->title("Match Specifications"); my @names=('Last Name','First Name','Not a name'); my $value=2; #no name is default my $indicator=0;#start looping over names, indicator=0=>Last, 1=>first +, 2=>no name %main::A={1=>['Tim','Doe','other_info1'], 2=>['Mick','Lu','other_info_2']}; %main::B={1=>['Timothy','Doe','other_info1','moreinfo1'], 2=>['Michail','Lu','other_info_2','moreinfo2']}; $main::headers[0]=['F','L','O']; $main::headers[1]=['M','J','P','JJ']; my $fr=$top->Frame(-relief=>'sunken')->pack(-anchor=>'nw',-fill=>'both +'); my $counter0=0; my @selector; my $col=0;my $colshow=0; my @keys00=sort keys %main::A;my @keys0=(); push @keys0,$keys00[0]; push @keys0,$keys00[1]; my @keys200=sort keys %main::B; my @keys20=(); push @keys20,$keys200[0]; push @keys20,$keys200[1]; my $row1=0; foreach my $el(@{$main::headers[0]}){ my $row=0; $selector[$col]=$fr->Scrolled('BrowseEntry',-label=>$el,-variable=>\$ +main::matchhash{$col}, -browsecmd=>[\&show,$el,\@headers2,\@keys200]); my $h2cnt=0 ; my $h2cntall=0; ##### this is the part that must be repopulated dynamically foreach my $el2(@{$main::headers[1]}){ $selector[$col]->insert("end", $el2); $h2cnt++; $h2cntall++;}#foreach el2 $selector[$col]->grid(-row=>$row,-column=>$colshow); #### end of part to repopulate dynamically $row++; #row nonzero $fr->Label(-text=>$main::A{$keys0[0]}->[$col])->grid(-row=>$row,-colum +n=>$colshow);$row++; $fr->Label(-text=>$main::A{$keys0[1]}->[$col])->grid(-row=>$row,-colum +n=>$colshow);$row++; foreach my $name(@names){ $fr->RadioButton( -text=>$name,-variable=>\$indicator,-value=>$value) +->grid(-row=>$row, -column=>$colshow); $row++;} $colshow++; $row1=$row; $col++;}#foreach el ####### $fr->Button(-text=>'Run',-bg=> 'firebrick1' ,-command=>sub{ } ) +->grid(-row=>$row1,-column=>1); &MainLoop(); sub show{my $el=shift; my $rheaders=shift; my $rkeys=shift; }
Perl variable scoping between functions
4 direct replies — Read more / Contribute
by Bryan882
on Jul 18, 2018 at 05:42
    Hello monks, I am somewhat confused at the behaviour of the code from within this perl script which I am trying to create. In short it is a function which will take a file specified at runtime and put it into a list. What you can see below is that I have it working from within the function but it doesn't seem to work correctly when i call it from another function and try to put it into an array etc.
    sub fLoadModules { my ($modules) = @_; open my $fh, "<", $modules or die "Couldn't open module file: $mod +ules"; while(<$fh>) { chomp; my ($module_id) = split /;/; print Dumper($module_id); } close $fh; }
    its also worth mentioning that $modules is declared in main, which will send the file path to this function above. The data will print within the sub but when called from another sub it runs into difficulty.
Perl logical operators
4 direct replies — Read more / Contribute
by Sogalei
on Jul 18, 2018 at 02:33

    Question: Logical operators giving wrong results. The results are only correct when $a is true and $b is false. Any advice to fix this?

    $a = false; $b = true; print "Value of \$a = $a and value of \$b = $b\n"; $c = ($a and $b); print "Value of \$a and \$b = $c\n"; $c = ($a && $b); print "Value of \$a && \$b = $c\n"; $c = ($a or $b); print "Value of \$a or \$b = $c\n"; $c = ($a || $b); print "Value of \$a || \$b = $c\n"; $a = 0; $c = not($a); print "Value of not(\$a)= $c\n"; ***Result*** Value of $a = false and value of $b = true Value of $a and $b = true Value of $a && $b = true Value of $a or $b = false Value of $a || $b = false Value of not($a)= 1
Syntax Perl Version support $c = () = $a =~ /\./g
6 direct replies — Read more / Contribute
by h2
on Jul 17, 2018 at 14:02

    Hi Perl Monks, I have what is hopefully a simple question, but one I have been unable to search for due to the odd syntax of the below.

    The program I'm working on has a core requirement to work on older systems, and has a cutoff of Perl 5.008 (selected because Redhat mid 2000s release was quite late to support 5.010) or newer, though that could change in the future to either a touch earlier version, or a touch later version (but certainly never newer as max oldest than 5.010). As an aside, so far Perl 5.x has far exceeded my wildest expectations in this regard, the program is in fact working on everything! No matter how weird or arcane.

    my $a='3.4.4'; my $c = () = $a =~ /\./g; print "$c\n"

    However, my question is this: when did Perl begin supporting this type of structure?

    $c = () = $a =~ /\./g

    I've come across this several times, and I'm allured by it, it calls to me, but I have to be careful using structures that could trigger warnings or failures in old systems.

    I'd actually like to significantly expand my use of this type of structure, so besides this specific example, can anyone point me to the right search terms that describe it, that's multiple assignments of some value generated on the right side of the items? And also I believe various items that could be in the second position, (), though I'm not positive about that. And has this support been consistent since version Are there various types of this assignment that have been introduced earlier or later?

    I have the big Larry Walls Perl book, but I don't know what this is called to begin learning more about it, and what variants will be safe to use.

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.