Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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
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 2.9.0.0 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/CGI.pm line 308. Use of uninitialized value $min in subtraction (-) at /Library/Perl/5.18/GD/Graph/histogram.pm line 110, line 1. Use of uninitialized value $max in subtraction (-) at /Library/Perl/5.18/GD/Graph/histogram.pm line 110, line 1. Use of uninitialized value $max in numeric le (<=) at /Library/Perl/5.18/GD/Graph/histogram.pm line 118, line 1. Use of uninitialized value $upper in numeric le (<=) at /Library/Perl/5.18/GD/Graph/histogram.pm line 118, line 1. Use of uninitialized value $lower in addition (+) at /Library/Perl/5.18/GD/Graph/histogram.pm line 119, line 1. Use of uninitialized value $max in numeric le (<=) at /Library/Perl/5.18/GD/Graph/histogram.pm line 122, line 1. Use of uninitialized value in string eq at /Library/Perl/5.18/GD/Graph/histogram.pm line 42, line 1. Use of uninitialized value in subtraction (-) at /Library/Perl/5.18/GD/Graph/histogram.pm line 59, line 1. Use of uninitialized value in addition (+) at /Library/Perl/5.18/GD/Graph/histogram.pm 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,

    GoodEvening

    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):

    A1,B1,ACTDATE,DEACTDATE

    7900724666,200906888,20180406,20180411

    7900724666,200906888,20180416,20180522

    7900724666,200906888,20180601,20180720

    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

    7900724677,200906871,20180101,20180228

    7900724677,200906872,20180301,20180330

    7900724677,200906873,20180401,20180420

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

    7900724688,200906881,20180101,20180228

    7900724688,200906881,20180303,20180330

    7900724688,200906882,20180404,20180430

    7900724688,200906883,20180508,20180620

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

    7900724699,200906891,20180101,20180228

    7900724699,200906891,20180303,20180330

    7900724699,200906892,20180404,20180430

    7900724699,200906893,20180508,

    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 5.xxx? 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.

Using Perl XS in 5.26 fails with error loadable library and perl binaries are mismatched
3 direct replies — Read more / Contribute
by jobinjoseph121
on Jul 17, 2018 at 08:35
    Hi,

    We have build Perl 5.26.1 from source and used the same Perl to create a perlmodule.c file from an XS file perlmodule.xs. But when we try to execute this C code, we get the following error.
    ../perlmodule.c: loadable library and perl binaries are mismatched (got handshake key 0xe280080, needed 0xde00080)

    Previously we were using Perl 5.16 and there were no issues. Could you please let us know whether we need to rewrite the XS module for Perl 5.26. Currently we are using the same XS module which is used in Perl 5.16. I am not sure if that is creating the issue here.

    We are generating the .c files with following command.
    perl ExtUtils/xsubpp -typemap typemap -typemap ExtUtils/typemap perlmodule.xs > perlmodule.cpp

    Following is the configuration details.

    Summary of my perl5 (revision 5 version 26 subversion 1) configuration +: Platform: osname=linux osvers=2.6.16.21-0.8-default archname=x86_64-linux-thread-multi uname='linux 2.6.16.21-0.8-default #1 mon jul 3 18:25:39 utc 2006 +x86_64 x86_64 x86_64 gnulinux ' config_args='-d -s -e -U uselargefiles -U use64bitint -U usemorebi +ts -D usemultiplicity -D usethreads -D prefix=/opt/perl/a -D installu +srbinperl=no -D useshrplib -D ccflags= -D libperl=libperl.so -D man1d +ir= -D perladmin=none -D pager=/usr/bin/less -D otherlibdirs=/opt/pe +rl/a/lib/site_perl' hint=recommended useposix=true d_sigaction=define useithreads=define usemultiplicity=define use64bitint=define use64bitall=define uselongdouble=undef usemymalloc=n default_inc_excludes_dot=define bincompat5005=undef Compiler: cc='cc' ccflags ='-D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe -f +stack-protector -I/usr/local/include -D_FORTIFY_SOURCE=2' optimize='-O2' cppflags='-D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe -f +stack-protector -I/usr/local/include' ccversion='' gccversion='4.1.0 (SUSE Linux)' gccosandvers='' intsize=4 longsize=8 ptrsize=8 doublesize=8 byteorder=12345678 doublekind=3 d_longlong=define longlongsize=8 d_longdbl=define longdblsize=16 longdblkind=3 ivtype='long' ivsize=8 nvtype='double' nvsize=8 Off_t='off_t' lseeksize=8 alignbytes=8 prototype=define Linker and Libraries: ld='cc' ldflags =' -fstack-protector -L/usr/local/lib' libpth=/usr/local/lib /usr/lib64/gcc/x86_64-suse-linux/4.1.0/../.. +/../../x86_64-suse-linux/lib /usr/lib /lib/../lib64 /usr/lib/../lib64 + /lib /lib64 /usr/lib64 /usr/local/lib64 libs=-lpthread -lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc -lgdb +m_compat perllibs=-lpthread -lnsl -ldl -lm -lcrypt -lutil -lc libc=libc-2.4.so so=so useshrplib=true libperl=libperl.so gnulibc_version='2.4' Dynamic Linking: dlsrc=dl_dlopen.xs dlext=so d_dlsymun=undef ccdlflags='-Wl,-E -Wl,-rpath,/opt/perl/a/lib/5.26.1/x86_64-linux-t +hread-multi/CORE' cccdlflags='-fPIC' lddlflags='-shared -O2 -L/usr/local/lib -fstack-protector' Characteristics of this binary (from libperl): Compile-time options: HAS_TIMES MULTIPLICITY PERLIO_LAYERS PERL_COPY_ON_WRITE PERL_DONT_CREATE_GVSV PERL_IMPLICIT_CONTEXT PERL_MALLOC_WRAP PERL_OP_PARENT PERL_PRESERVE_IVUV USE_64_BIT_ALL USE_64_BIT_INT USE_ITHREADS USE_LOCALE USE_LOCALE_COLLATE USE_LOCALE_CTYPE USE_LOCALE_NUMERIC USE_LOCALE_TIME USE_PERLIO USE_PERL_ATOF USE_REENTRANT_API Built under linux

    Thanks and Regards,
    Jobin Joseph
regex find and replace with a twist
3 direct replies — Read more / Contribute
by Anonymous Monk
on Jul 17, 2018 at 00:32

    How do I find and replace every letter in a word with a modified version of the word? Basically I need to find any letter [a-zA-Z] and replace it with [aA][zZ]. For Example:

    my $word = "layer" my $new_word = "[l][a][y][e][r]"

    2018-07-17 Athanasius added code tags within text


Add your question
Title:
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?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others browsing the Monastery: (2)
    As of 2018-07-19 04:34 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















      Results (402 votes). Check out past polls.

      Notices?