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
DBIx::Class 'select.... for update' confusion
1 direct reply — Read more / Contribute
by tomgracey
on Dec 14, 2017 at 16:17

    Hello all

    I am confused about the mechanics of 'select.. for update' under DBIx::Class (I'm using MySQL but I suppose that shouldn't matter.) So I have reduced it down to the following test case:

    my $guard = $schema->txn_scope_guard; my $rs = $schema->resultset('TestTable')->search({ status => 'available' }, { rows => 1, 'for' => 'update' }); my $id_before_update = $rs->first->id; my $updated = $rs->update({ status => 'reserved' }); $guard->commit; my $id_at_end = $rs->first->id; print "id before update: $id_before_update\nid at end: $id_at_end\n";
    The table looks like this initially:
    +----+-----------+ | id | status | +----+-----------+ | 1 | available | | 2 | available | | 3 | available | +----+-----------+

    and after execution like this:

    +----+-----------+ | id | status | +----+-----------+ | 1 | reserved | | 2 | available | | 3 | available | +----+-----------+

    The schema was created by DBIx::Class::Schema::Loader and looks like this:

    __PACKAGE__->table("test_table"); __PACKAGE__->add_columns( "id", { data_type => "bigint", is_nullable => 0 }, "status", { data_type => "varchar", is_nullable => 1, size => 255 }, );
    (with boilerplate removed). When I run the above code I get the following:
    id before update: 1 id at end: 2

    To me this seems like odd behaviour, because after $rs is selected with rows=1 it surely should only contain a single row with a single id...?

    Any idea what stupid thing have I (not) done this time?

Perl <dir_with_wildcards>
1 direct reply — Read more / Contribute
by haroyken
on Dec 14, 2017 at 02:36

    O wise monks I beseech thy help in understanding this snippet of perl:

    Basically I had files stores in multiple dir and want to assign the location of these files to an array

    E.g.

    /home/a1/data/loga1.txt (data also contains other files with different extension)

    /home/b2/data/logb2.txt

    /home/c3/data/logc3.txt

     my @array = </home/*/data/*.txt>;

    does the job but I don't understand why

    Normally I've seen the diamond operator with STDIN, etc. or filehandle. How does it work with a directories with wildcards like this ?

    Thank you very much

Why does "cpan -r" download new modules?
2 direct replies — Read more / Contribute
by jimav
on Dec 14, 2017 at 00:20

    What exactly is "cpan -r" supposed to do? The man page says it runs CPAN::Shell->recompile and perldoc CPAN says recompile() should recompile XS code for all installed dynamically-linked extensions. But in fact, it seems to download and install many other modules I never installed!

    To be sure I wasn't hallucinating, I created a brand-new user with an empty home directory, used local::lib to set up a local cpan build environment. Then ran "cpan -r" expecting it to do nothing because the new user had never installed any CPAN modules. However, it proceeded to download and install zillions of modules, until it finally failed with some unmet dependency. What causes this!?!

    Can someone explain (or point me to documentation explaining) where "cpan -r" looks to decide what modules to update, and what is the correct procedure for just rebuilding the XS code for only the modules I previously installed? Really, I just want to recover from XS breakage due to perl being updated (during an OS upgrade).

    BTW, I just did a clean Ubuntu 17.10 install (preserving only /home), so the system perl installation and library are pristine. And I never ran cpan as root, so there is no way it could have damaged the system setup (assuming there isn't a suid program lurking somewhere in cpan)

    Here's what I did:

    #Create a new user with pristine environment
    $ sudo adduser test  
    $ sudo rm -f /home/test/.*   # get rid of .profile or any other influence
    $ sudo su - test
    $ ls -a
    .  ..  .bash_history 
    # set up ~/perl5 and set environment vars for local cpan library
    $ eval "$(perl -I/path/to/other/user/perl5 -Mlocal::lib)
    $ env | grep -i PERL
    PERL_MB_OPT=--install_base "/home/test/perl5"
    PERL_MM_OPT=INSTALL_BASE=/home/test/perl5
    PERL_LOCAL_LIB_ROOT=/home/test/perl5
    PERL5LIB=/home/test/perl5/lib/perl5
    PATH=/home/test/perl5/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin
    
    # set up cpan for local builds
    $ cpan
    Sorry, we have to rerun the configuration dialog for CPAN.pm due to
    some missing parameters. Configuration will be written to
     <</home/test/.cpan/CPAN/MyConfig.pm>>
    CPAN.pm requires configuration, but most of it can be done automatically.
    If you answer 'no' below, you will enter an interactive dialog for each
    configuration option instead.
    Would you like to configure as much as possible automatically? yes I hit Enter
    Autoconfiguration complete.
    commit: wrote '/home/test/.cpan/CPAN/MyConfig.pm'
    ...
    quit
    
    # Now the craziness begins...
    # Since this test user has never installed any CPAN modules, I expected
    # "cpan -r" to do nothing.  But...
    $ cpan -r
    Loading internal null logger. Install Log::Log4perl for logging messages
    Fetching with LWP:
    http://www.cpan.org/authors/01mailrc.txt.gz
    Reading '/home/test/.cpan/sources/authors/01mailrc.txt.gz'
    ............................................................................DONE
    Fetching with LWP:
    http://www.cpan.org/modules/02packages.details.txt.gz
    Reading '/home/test/.cpan/sources/modules/02packages.details.txt.gz'
      Database was generated on Thu, 14 Dec 2017 04:29:02 GMT
    ............................................................................DONE
    Fetching with LWP:
    http://www.cpan.org/modules/03modlist.data.gz
    Reading '/home/test/.cpan/sources/modules/03modlist.data.gz'
    DONE
    Writing /home/test/.cpan/Metadata
    .......................................................
      CPAN: Recompiling A/AM/AMS/Storable-2.51.tar.gz
    
    Fetching with LWP:
    http://www.cpan.org/authors/id/A/AM/AMS/Storable-2.51.tar.gz
    Fetching with LWP:
    http://www.cpan.org/authors/id/A/AM/AMS/CHECKSUMS
    Checksum for /home/test/.cpan/sources/authors/id/A/AM/AMS/Storable-2.51.tar.gz ok
    'YAML' not installed, will not store persistent state
    Configuring A/AM/AMS/Storable-2.51.tar.gz with Makefile.PL
    Checking if your kit is complete...
    Looks good
    Generating a Unix-style Makefile
    Writing Makefile for Storable
    Writing MYMETA.yml and MYMETA.json
      AMS/Storable-2.51.tar.gz
      /usr/bin/perl Makefile.PL INSTALLDIRS=site -- OK
    Running make for A/AM/AMS/Storable-2.51.tar.gz
    cp Storable.pm blib/lib/Storable.pm
    Running Mkbootstrap for Storable ()
    chmod 644 "Storable.bs"
    "/usr/bin/perl" -MExtUtils::Command::MM -e 'cp_nonempty' -- Storable.bs blib/arch/auto/Storable/Storable.bs 644
    "/usr/bin/perl" "/usr/share/perl/5.26/ExtUtils/xsubpp"  -typemap '/usr/share/perl/5.26/ExtUtils/typemap'  Storable.xs > Storable.xsc
    mv Storable.xsc Storable.c
    x86_64-linux-gnu-gcc -c   -D_REENTRANT -D_GNU_SOURCE -DDEBIAN -fwrapv -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O2 -g   -DVERSION=\"2.51\" -DXS_VERSION=\"2.51\" -fPIC "-I/usr/lib/x86_64-linux-gnu/perl/5.26/CORE"   Storable.c ...
    <and much more>
    
    ...Eventually it died with some unsatisfied dependency...
    
    Fetching with LWP:
    http://www.cpan.org/authors/id/X/XA/XAOC/Pango-1.227.tar.gz
    Checksum for /home/test/.cpan/sources/authors/id/X/XA/XAOC/Pango-1.227.tar.gz ok
    ---- Unsatisfied dependencies detected during ----
    ----          XAOC/Pango-1.227.tar.gz         ----
        ExtUtils::Depends build_requires
        ExtUtils::PkgConfig build_requires
    
Problem creating http request string using apostrophe
1 direct reply — Read more / Contribute
by Bloehdian
on Dec 13, 2017 at 19:33

    Hi all,

    the following script should send an http-request to httpbin.org. But it fails with the creation of the proper request string, probably since the script interprets it as a sequence of namespaces separated in the old style using apostrophe. What am I doing wrong?

    #!/usr/bin/perl use strict; use REST::Client; my $client = REST::Client->new(); my $request=q{DELETE('https://www.httpbin.org/delete')}; print $request; eval( $client->$request ); print $client->responseCode();

    Execution leads to the following

    Can't locate object method ")" via package "DELETE('https://www.httpbin.org/delete" (perhaps you forgot to load "DELETE('https://www.httpbin.org/delete"?) at test.pl line 7.
[SOLVED] Using Perlbrew with debian Perl packages like libdbd-mysql
2 direct replies — Read more / Contribute
by nysus
on Dec 13, 2017 at 14:31

    I've got perlbrew installed on a development machine running an older version of perl. On my debian box, I used system perl, using the debian package manager, to get mysql installed. I now want to install DBD::mysql so my perlbrew scripts can use it. I can install the Debian libdbd-mysql package and get it installed system wide easily. But, of course, my scripts running on the Perlbrew version of perl know nothing about their existence and so can't use the perl packages installed by libdbd-mysql. And when I try to install DBD::mysql with perlbrew, I get configuration errors.

    So what's the most painless way of getting perlbrew to work with DBD::mysql? Is there a way to get it to use the system wide DBD::mysql package that won't break things? Thanks!

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

How to set 'max_len' for DBI 'bind_param'
4 direct replies — Read more / Contribute
by JamesK3
on Dec 13, 2017 at 11:01
    Great and wise Perl monks,

    I'm a Perl novice still endeavoring through my journey to your great and vaunted status.

    How the heck do I set a 'max_len' parameter when using DBI and 'bind_param'?

    I'm encountering an issue where one of the parameters that I'm attempting to bind can be over thousands of characters long and exceeding the default maxlen and flowing into the next parameter. Below is what I'm seeing in my DBI 'trace.txt':
    bd_bind_ph(1): bind :p52 <== ''James K3Home AddressCity, State 28301Ja +mes.K3@address.comPhone: (111)111-1111OBJECTIVEPursuing a position th +at would allow me to utilize my computer skills while allowing me to +contribute to a dynamic business environment.SKILLSLinux administrati +on (CentOS/Ubuntu)Writing and maintaining Bash scripts Writing and ma +intaining Perl scriptsWriting and maintaining Standard Operating Proc +eduresVMWare ESXiEMC Unisphere Management (VNXe) Server RackingProfic +ient in Windows and Linux systems administrationPhone/Network cabling +EXPERIENCE As a Systems Administrator with the CompanyImWith I am res +ponsible for maintining a wide array of infrastructure, ensuring that + system security and maintenance is maintained without negatively imp +acting production workflows. In my current role my team and I manage + 270 servers, working with ESXi 5.5, Oracle Enterprise Linux (5.8 . 6 +.6), as well as Server 2000 . 2012r2. While with CompanyImWith I hav +e taken the lead on implementing monitorin...' (type 0 (DEFAULT (varc +har))) dbd_rebind_ph_char() (1): bind :p52 <== ''Jame...' (size 3746/3752/0, +ptype 5(LONG), otype 8 ) dbd_rebind_ph_char() (2): bind :p52 <== ''Jame...' (size 3746/3752, ot +ype 8(LONG), indp 0, at_exec 1) bind :p52 as ftype 8 (LONG) dbd_rebind_ph(): bind :p52 <== ''Jame...' (in, not-utf8, csid 1->0->1, + ftype 8 (LONG), csform 0(0)->0(0), maxlen 3752, maxdata_size 0) dbd_bind_ph(1): bind :p53 <== ' ensuring proper adherence to the dicta +tes of the NISPOM while assisting the customer in maintaining mission + readiness and accomplishment. In my role as the AFSO I assiste
    TIA!
    James
Lossing session value
3 direct replies — Read more / Contribute
by Anonymous Monk
on Dec 13, 2017 at 10:46
    Hi Monks!

    When I am using "Location:" to redirect the page to its original state and to prevent re-sending the upload again.
    I am losing the value stored in the session, I need this value to display to the user the name of the file just uploaded.
    I cant understand why this happens? Why isn't the value in the session available once the Location gets called? Any suggestion why or a better why to do this?
    Here is a code prototype that shows what I am trying to do:

    #!/usr/bin/perl use strict; use warnings; use CGI; use HTML::Template; use Time::Piece; use CGI::Session; use Data::Dumper; my $date_ntime = localtime->strftime('%Y%m%d%H%M%S'); my $cgi = CGI->new(); # Create new session my $session = new CGI::Session("driver:File", undef, {Directory => 'se +sh'}) or die CGI::Session->errstr;; my $tmpl = HTML::Template->new(filename => 'templates/mini.tmpl', die_ +on_bad_params => 0, associate => $session); my $got_file_name = $cgi->param( 'doc_upload' ) || ''; # Store file name to use later. $session->param("doc_uploaded", $got_file_name); my $filename_uploaded = $session->param("doc_uploaded"); # This is the return from the redirect 'Location:' my $conf_msg = $cgi->param( 'conf' ) || ''; process_request($got_file_name, $date_ntime) if $got_file_name ; # To prevent re-entering data twice by refreshing page. confirmation($conf_msg) if $conf_msg; print $cgi->header, $tmpl->output; exit; sub process_request { my ($file_name, $date_ntime ) = @_; return unless $file_name ; my $file_renamed .=$date_ntime.".txt"; my ($ext) = $file_name =~ /((\.[^.\s]+)+)$/; if ($ext =~ m/\.txt|\.csv$/) { $cgi->upload( 'doc_upload' ); my $tmp_file = $cgi->tmpFileName( $file_name ); rename( $tmp_file, $file_renamed ); chmod 0664, $file_renamed; print 'Location: https://myserver/mini.pl?conf=1', "\r\n\r\n"; }else { $tmpl->param( ERROR => 1, ); } } sub confirmation { my ($message) = @_; return unless $message; my $text = $session->param("doc_uploaded"); #my $text = $session->param(-name=>'doc_uploaded'); $tmpl->param( MSG_OK => 1, #FILE_NAME => $text, FILE_NAME => $filename_uploaded, ) if $message; }

    Here is the template file:
    <!DOCTYPE html> <html lang="en"> <head> <title>Mini</title> </head> <body> <p><b>UP-load.</b></p> <form action="mini.pl" method="post" enctype="multipart/form-data"> <input type="file" size="40" name="doc_upload"> <input type="submit" name="doc_submit" value="Upload"> </p> </form> <br> <br> <TMPL_IF NAME="MSG_OK"> <p>Transaction was successful!</p> <p>Filename: <TMPL_VAR NAME="FILE_NAME"></p> </TMPL_IF> <TMPL_IF NAME="MSG"> <p>WARNING: file <TMPL_VAR NAME="FILE_NAME"> already exists.</p> <p>Check and try again.</p> </TMPL_IF> <TMPL_IF NAME="ERROR"> <p>Wrong file type.</p> </TMPL_IF> </body> </html>

    Thanks for looking!
Lingua::EN::Tagger adapting to other language
No replies — Read more | Post response
by Anonymous Monk
on Dec 13, 2017 at 10:15

    Hello

    I am trying a quite (for me) difficult task: adapt the module Lingua::EN::Tagger to be used with another language. To do so I need to train the probability values with a corpus in my language. The probability values are saved in several YAML files. Unfortunately there is 0 documentation, as far as I can say, describing how to do this. Actually, I have problems understanding how the probabilities are saved. I have some background in linguistics and in corpus linguistics. However, without documentation it is a hard task for me. I have seen that there is also a German version (Lingua::EN::Tagger) derived from the EN one. So the task, provided a corpus and some manual tagging to train the model, should be doable. I've written to the authors to get some info on how to proceed, but no response. Has somebody already tried to do something like this? If yes, have you found some documentation online on how to train the model? Any suggestion would be very much appreciated. Best.

How to use cgi table in newindex.pm perl
4 direct replies — Read more / Contribute
by Tabish
on Dec 13, 2017 at 05:54

    Hallo to everyone

    I treid to make cgi table in my newindex.pm to return data from hashref in a table in my test.pl but cant.

    I will appreciate when you give me some ideas or guide me. im new in perl! i also search alot and i know how to use cgi table in "test.pl" but not in "newindex.pm"

    Here is my code

    package newindex; use strict; sub getTitle { return "workers"; } sub getContent { my $cgi = shift; $hashref = { 'Adam' => 'Eve', 'Clyde' => 'Bonnie', }; my $table = ; return $table; } 1;

    test.pl

    #!"C:\xampp\perl\bin\perl.exe" use strict; use warnings; use CGI qw/:standard/; push @INC, "."; sub getHeaders { my $cgi = shift; return $cgi->header('text/html'); } sub getBody { my $cgi = shift; return $cgi->start_html( getContent($cgi,'title') ) . getContent($cg +i,'content') . $cgi->end_html; } sub getModule { my $cgi = shift; my $action = $cgi->param('action') // 'newindex'; $action = 'newindex' unless (-f $action.'.pm'); eval "use $action;"; return $action; } sub getContent { my ($cgi,$call) = @_; my $module = getModule($cgi); my $caller = 'get'.ucfirst($call); return $module->$caller($cgi); } sub main { my $cgi = new CGI; print getHeaders($cgi) . getBody($cgi); } main();
Re^2: using change directory within perl script
No replies — Read more | Post response
by Anonymous Monk
on Dec 12, 2017 at 22:19
    Hello Can you help me rewrite this part of code in different way. Here I want to open the "counters.conf" file in which I have the OID's (values like this): 1,10e6 2,5e6 3,100e6 4,1e9 50,10 55,124 I used hash function. Here I want to slipt the rows and if I call for example 55, it must return the value of 124. for example I can also use this :
    my ($row1, $row2)=split/,/,$row; $values{$row1}=$row2;
    How can I write this code in a different way? Code:
    my $filename = ('/tmp/A1/counters.conf'); open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!"; my %values=(); my $t=time(); while (my $row = <$fh>) { chomp $row; my ($row1, $row2) = split /\s*=\s*/,$row; $values{$row1}=$row2; } while (my ($n,$m) = each %values) { if ($OID2-1==$n){ my $var=$m*$t; $request->setValue(ASN_COUNTER,$var); } }

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.