Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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
Inherit methods from IO::File and IO::Uncompress depending on file extension
1 direct reply — Read more / Contribute
by jnoirel
on Apr 28, 2015 at 07:07

    Hi there,

    I'm trying to develop a package DATASTORE used like this

    $D = new DATASTORE 'dir', 'filename'; while($_ = $D->getline) { [...] }

    The added benefit of using DATASTORE (in case you're wondering) is that it does some work towards automatically locating the data files I want based on some local config. I'd like the $D variable to inherit all the methods from IO::File.

    package DATASTORE; use parent 'IO::File'; sub new { my ($class, @args) = @_; my $filename; [...] $self = $class->SUPER::new($filename, 'r'); return $self if defined $self; }

    That seems to work for me. Now what I'm not sure about is how you'd adapt the code so that depending on the extension, it uses IO::File OR IO::Uncompress::Gunzip (if the extension is GZ).

    Would this be something that's easy to do?


Printing hash key shows obscure values - can this be trimmed/removed?
2 direct replies — Read more / Contribute
by yasmarina
on Apr 28, 2015 at 07:04

    Am reading in x2 TAB delimited text files. I'd like to compare the differences of a value from these x2 files then show the entire records of the differences. I have 2 key defined:

    sub Read_File { my $FILE = shift ; open (my $fh, "<", $FILE) || die "$!" ; my %hRec ; while (<$fh>) { chomp; my @RecLine=split (/;/) ; my @RecLine=split ('\t') ; $CmpKey=$RecLine[$Key] ; $CmpKey2=$RecLine[$Key2] ; $CmpValue=$RecLine[$Cmp] ; $hRec{$CmpKey,";",$CmpKey2}=$CmpValue; } return (%hRec) ; } foreach my $key (sort {$a<=>$b} keys %hBase) { print "$key -> $hBase{ +$key}\n"; } foreach my $key (sort {$a<=>$b} keys %hPost) { print "$key -> $hPost{ +$key}\n"; }

    The above will print the keys & value. But I get this weird white-space '^\'?

    NR^\;^\INVOICE_TXT -> CHARGE 1^\;^\Access Charge -> .083 1^\;^\Service Charge -> .042 2^\;^\Access Charge -> .083 2^\;^\Service Charge -> 0
    How can I remove the '^\' ? Thanks
Is tie inteded to be used in this way?
No replies — Read more | Post response
by Discipulus
on Apr 28, 2015 at 07:01
    suppose i have an array and i wont to trigger some action when some of the element are modified, but not when they are accessed.
    i discovered the tie ability of Perl and seems appropriate:

    Is intended to be used in this way?
    #!perl use strict; use warnings; {#bare block because package BLOCK appeared only 5.14 package Arraytrigger; use Tie::Array; use vars qw(@ISA); @ISA = ('Tie::StdArray'); sub STORE { &main::trigger; my $self = shift; $self->SUPER::STORE($self, @_); } sub CLEAR { &main::trigger; my $self = shift; $self->SUPER::CLEAR ($self, @_); } sub PUSH { &main::trigger; my $self = shift; $self->SUPER::PUSH($self, @_); } sub POP { &main::trigger; my $self = shift; $self->SUPER::POP($self, @_); } sub SHIFT { &main::trigger; my $self = shift; $self->SUPER::SHIFT($self, @_); } sub UNSHIFT { &main::trigger; my $self = shift; $self->SUPER::UNSHIFT($self, @_); } } #package main.. sub trigger{print "Triggered [@_]\n"} tie my @arr, 'Arraytrigger'; print "\tSetting list:\n" and @arr = qw(a b c d e); print "\tSetting one:\n" and $arr[0]=0; print "\tpushing:\n" and push @arr,'f'; print "\tpopping:\n" and pop @arr; print "\tshifting:\n" and shift @arr; print "\tunshifting:\n" and unshift @arr, 'zero'; print "\tclearing:\n" and @arr=();#undef @arr and @arr=undef see +m no good..

    Or can i avoid all the repeted code in this other way?

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Passing application data in PSGI env
1 direct reply — Read more / Contribute
by roman
on Apr 28, 2015 at 04:54

    Dear Monks,

    there are couple of middleware modules passing some application data via $env.

    They may set logger ($env->{'psgix.logger'}), parsed content ($env->{''}), information whether page is fetched by robot ( $env->{robot_content} ), they may pass router or route match ($env->{'ox.router'}), ...

    Is there any general convention for naming of such keys? Prefix them with the application ($env->{'myapp.router'}) and keep them flat? Keep them in one nested structure ($env->{myapp})? This way resemble stash (Catalyst or other) to me.

    Do you think it is a good practice?

    There is even a middleware (Plack::Middleware::FormatOutput) which use a kind of application data in body. Plack::Middleware::FormatOutput formats data returned by the wrapped application in body (third argument of psgi triplet).

    While the idea of formatter implementation via middleware seems tempting, is it still middleware (the body part of triplet is neither arrayref, nor filehandle)? What do you think about such idea?

Renaming Every File in a directory
3 direct replies — Read more / Contribute
by Anonymous Monk
on Apr 27, 2015 at 23:38
    I have this code to delete every file in a directory and skip directories... but I'm not remembering how to use the sub to rename files...

    #!/usr/bin/perl use CGI qw(:standard); use strict; use File::Find; use vars qw($_amountOfFiles); my $_excludeList = 1; my $_expcludeMain = 1; my $dir = "/home/path/public_html/files"; my %_excludeListing = ( 'cgi-bin' => "cgi-bin", ); #my $dir = shift || die "usage $0 <dir>\n"; print "Content-type: text/plain\n\n"; $_amountOfFiles = 0; finddepth(\&do_this, $dir); print "Renamed: $_amountOfFiles files\nDone\n"; #rmdir $dir; sub do_this { # ignore . and .. return if /^\.\.?$/; if (-d) { if($_excludeList && exists($_excludeListing{$_})) { print "Skipping dir: $File::Find::name\n"; return; } if($_expcludeMain && $_ eq "$dir") { print "Skipping dir: $File::Find::name\n"; return; } # print "Removing dir: $File::Find::name\n"; # rmdir; } else { print "."; $_amountOfFiles++; unlink; } }

    Where unlink is, what do I put to rename the file, IF it ends in .jpg to a Random string.jpg?

    Instead of unlink?

    I have not been writing Perl programming for a few years, and I feel like I'm getting dementia... I am at a total loss on it.

    Can you point me in the right direction?

Cross Database Access not supported
2 direct replies — Read more / Contribute
by Bio_ftr
on Apr 27, 2015 at 21:09
    I am connecting to a netzezza database using ODBC. I have worked on this tiny bit of code for a few days and I keep getting an error:
    DBD::ODBC::st execute failed: ERROR: Cross Database Access not supported for this type of command (SQL-HY000) at line 20.

    Line 20 is $sth-> execute(). I am not crossing databases so I don't understand what is causing this error. I can replace the update statement with a select, and the program runs correctly.

    This is the code:

    use strict;
    use warnings;
    use DBI;
    use DBD::ODBC;

    my $dbh = DBI-> connect('dbi:ODBC:system', 'user', 'pwd') or die "Couldn't connect to database: " . DBI->errstr;

    my $stmt= "update db_name.user.table_name set column_name= 8 where column_name2 like 'someValue'";
    #my $stmt= "select column_name1, column_name2 from db_name.user.table_name where column_name2 like 'anotherValue'";

    my $sth;
    $sth = $dbh->prepare($stmt) or die "Couldn't prepare statement:". $dbh->errstr;
    $sth-> execute() #Execute the query or die "Couldn't execute statement:".$dbh->errstr;
    use DBI;

unable to establish SMTP connection
3 direct replies — Read more / Contribute
by perl_dan
on Apr 27, 2015 at 15:32
    I run a single computer from home. OS is W8.1 Pro and I program and execute on DwimPerl. The following code:
    #!/usr/bin/perl use 5.010; use Email::MIME; my $message = Email::MIME->create( header_str => [ From => '', To => '', Subject => 'Happy birthday!', ], attributes => { encoding => 'quoted-printable', charset => 'ISO-8859-1', }, body_str => "Happy birthday to you!\n", ); # send the message use Email::Sender::Simple qw(sendmail); sendmail($message);
    results in:
    "unable to establish SMTP connection Trace begun at C:\Dwimperl\perl\site\lib\Email\Sender\Transport\SMTP.p +m line 95 Email::Sender::Transport::SMTP::_throw('Email::Sender::Transport::SMTP +=HASH(0x2cf10dc)', 'unable to establish SMTP connection') called at C +:\Dwimperl\perl\site\lib\Email\Sender\Transport\ line 62 Email::Sender::Transport::SMTP::_smtp_client('Email::Sender::Transport +::SMTP=HASH(0x2cf10dc)') called at C:\Dwimperl\perl\site\lib\Email\Se +nder\Transport\ line 104 Email::Sender::Transport::SMTP::send_email('Email::Sender::Transport:: +SMTP=HASH(0x2cf10dc)', 'Email::Abstract=ARRAY(0x41fd64)', 'HASH(0x41f +d74)') called at C:\Dwimperl\perl\site\lib\Email\Sender\Role\ line 27 Email::Sender::Role::CommonSending::__ANON__ at C:\Dwimperl\perl\site\ +lib\Try\ line 76 eval {...} at C:\Dwimperl\perl\site\lib\Try\ line 67 Try::Tiny::try('CODE(0x2e37d44)', 'Try::Tiny::Catch=REF(0x2cce4ec)') c +alled at C:\Dwimperl\perl\site\lib\Email\Sender\Role\ + line 37 Email::Sender::Role::CommonSending::send('Email::Sender::Transport::SM +TP=HASH(0x2cf10dc)', 'Email::Abstract=ARRAY(0x41fd64)', 'HASH(0x2e37f +44)') called at C:\Dwimperl\perl\site\lib\Email\Sender\Simple .pm line 110 Email::Sender::Simple::send_email('Email::Sender::Simple', 'Email::Abs +tract=ARRAY(0x41fd64)', 'HASH(0x41fe54)') called at C:\Dwimperl\perl\ +site\lib\Email\Sender\Role\ line 27 Email::Sender::Role::CommonSending::__ANON__ at C:\Dwimperl\perl\site\ +lib\Try\ line 76 eval {...} at C:\Dwimperl\perl\site\lib\Try\ line 67 Try::Tiny::try('CODE(0x41fde4)', 'Try::Tiny::Catch=REF(0x2b8b6cc)') ca +lled at C:\Dwimperl\perl\site\lib\Email\Sender\Role\ +line 37 Email::Sender::Role::CommonSending::send('Email::Sender::Simple', 'Ema +il::MIME=HASH(0x2ceab2c)') called at C:\Dwimperl\perl\site\lib\Sub\Ex +porter\ line 69 Sub::Exporter::Util::__ANON__('Email::MIME=HASH(0x2ceab2c)') called at + line 21 Press any key to continue . . ."
    What's missing?
Ubuntu 14.04.1 & Net::SSLGlue::POP3
1 direct reply — Read more / Contribute
by JimSi
on Apr 27, 2015 at 12:53

    I have a problem compiling or installing Net::SSLGlue / Net::SSLGlue::POP3 package on newest Ubuntu 14.04.1. Never had any problem with it on CentOS and the script works right there. On Ubuntu - if I install from package (apt) - it cannot run the script, and gave me following error:

    $ ./t.perl Subroutine Net::POP3::starttls redefined at /usr/share/perl5/Net/SSLGl +ue/ line 13. Subroutine Net::POP3::_STLS redefined at /usr/share/perl5/Net/SSLGlue/ line 27. cannot find and replace IO::Socket::INET superclass at /usr/share/perl +5/Net/SSLGlue/ line 93. Compilation failed in require at ./t.perl line 21. BEGIN failed--compilation aborted at ./t.perl line 21.

    when I am trying to install from CPAN:
    PERL_DL_NONLAZY=1 "/usr/bin/perl" "-MExtUtils::Command::MM" "-MTest::H +arness" "-e" "undef *Test::Harness::Switches; test_harness(0, 'blib/l +ib', 'blib/arch')" t/*.t t/01_load.t .. Subroutine Net::SMTP::starttls redefined at /root/.cpan +/build/Net-SSLGlue-1.053-fRXdxl/blib/lib/Net/SSLGlue/ line 13. Subroutine Net::SMTP::_STARTTLS redefined at /root/.cpan/build/Net-SSL +Glue-1.053-fRXdxl/blib/lib/Net/SSLGlue/ line 30. t/01_load.t .. Failed 1/3 subtests Test Summary Report ------------------- t/01_load.t (Wstat: 0 Tests: 3 Failed: 1) Failed test: 1 Files=1, Tests=3, 1 wallclock secs ( 0.02 usr 0.00 sys + 0.10 cusr + 0.00 csys = 0.12 CPU) Result: FAIL Failed 1/1 test programs. 1/3 subtests failed. make: *** [test_dynamic] Error 255

    The script fails to load "Net::SSLGlue::POP3" module.
    Please help
Efficient Automation
4 direct replies — Read more / Contribute
by jmneedhamco
on Apr 27, 2015 at 11:29

    I am working on a script to automate some process checking and basically want the script to check processes and then if one is not running, start it.

    There are several instances of Apache for example that are running for various groups in our company. So I envision a for/each loop. This loop would check each process in turn and then if the ps command returns FAILURE, then it would launch that start command associated with that process.

    The question here is: Would the best approach be a couple of arrays with the cmds in them? The way to look at each process on this box is the same save the item we are grepping for.

    Help to do this in most efficient way is appreciated.

perlform ^* variable field length
2 direct replies — Read more / Contribute
by Anonymous Monk
on Apr 27, 2015 at 10:14

    Hello Monks, I'm using perl format to print variable field data fields having new lines

    #!/usr/bin/env perl use warnings; my $f = "format = \n" . ('^*' . '|') x 3 . "~~\n" . '@row' . "\n" . ".\n"; eval($f); my $f = "format = \n" . ('^*' . '|') x 3 . "~~\n" . '@row' . "\n" . ".\n"; eval($f); print $f, "\n"; my @row = ('line1 line3 ', 'line4 line5 line6 line7 ', 'line8' ); write; exit

    but this gives me weird results, when I reduce num cols to 2 then it works as per documentation. Need your help in getting this code work.


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!
  • 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
  • Outside of code tags, you may need to use entities for some characters:
            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 the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (14)
    As of 2015-04-28 13:06 GMT
    Find Nodes?
      Voting Booth?

      Who makes your decisions?

      Results (520 votes), past polls