Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

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
Perl version issue?
1 direct reply — Read more / Contribute
by T-Fen
on Oct 25, 2014 at 22:06

    Hello perl monks-

    I'm on a Mac and recently upgraded from Mavericks to Yosemite which might be the cause of my current issue.

    I am using mutt with t-prot and getting the following error when attempting to view a message in mutt (which invokes t-prot)

    'Can't locate Locale/ in @INC (you may need to install the Locale::gettext module) (@INC contains: /Library/Perl/5.12 /Library/Perl/5.18/darwin-thread-multi-2level /Library/Perl/5.18 /Network/Library/Perl/5.18/darwin-thread-multi-2level /Network/Library/Perl/5.18 /Library/Perl/Updates/5.18.2 /System/Library/Perl/5.18/darwin-thread-multi-2level /System/Library/Perl/5.18 /System/Library/Perl/Extras/5.18/darwin-thread-multi-2level /System/Library/Perl/Extras/5.18 .) at /usr/local/bin/t-prot line 1147.

    When i do a search for getttext, I see the following:

    /Library/Perl/5.16/darwin-thread-multi-2level/Locale/ /Library/Perl/5.16/darwin-thread-multi-2level/auto/Locale/gettext /Library/Perl/5.16/darwin-thread-multi-2level/auto/Locale/gettext/.pac +klist /Library/Perl/5.16/darwin-thread-multi-2level/auto/Locale/gettext/gett /Library/Perl/5.16/darwin-thread-multi-2level/auto/Locale/gettext/gett +ext.bundle /Previous System/Library/Perl/5.16/darwin-thread-multi-2level/auto/Loc +ale/gettext /Previous System/usr/local/Cellar/gettext/0.19.3/share/doc/gettext/exa +mples/hello-perl /Previous System/usr/local/Cellar/gettext/0.19.3/share/doc/gettext/exa +mples/hello-perl/m4 /Previous System/usr/local/Cellar/gettext/0.19.3/share/doc/gettext/exa +mples/hello-perl/po /usr/local/Cellar/gettext/0.19.3/share/doc/gettext/examples/hello-perl /usr/local/Cellar/gettext/0.19.3/share/doc/gettext/examples/hello-perl +/INSTALL /usr/local/Cellar/gettext/0.19.3/share/doc/gettext/examples/hello-perl +/ /usr/local/Cellar/gettext/0.19.3/share/doc/gettext/examples/hello-perl +/

    So seeing that @INC doesn't appear to look in /Library/Perl/5.16/ I then added the path using:

    $ PERL5LIB=/Library/Perl/5.16/darwin-thread-multi-2level/; export PERL5LIB

    Doing that, I now get this error when trying to view a message with mutt/t-prot:

    'Perl API version v5.16.0 of v5.16.0 does not match v5.18.0 at /System +/Library/Perl/5.18/darwin-thread-multi-2level/ line 217. + + + Compilation failed in req +uire at /usr/local/bin/t-prot line 1147.

    /Library/Perl/ contains a /5.16 and a /5.18 directory but looks like anything related to gettext is only in /5.16. Looking for guidance on how to fix this so that the needed files are found.


how to extract script output in new text file ?
4 direct replies — Read more / Contribute
by Chris202
on Oct 25, 2014 at 13:19
    Dear all I own nothing but faith in you all because I have tried to find the answer to my question on the internet for long but couldn't get (or understand) it... Here's my problem: I have a script that scans throught a text file and writes all line except those starting with an A.
    #!/usr/bin/perl use strict; use warnings; open (my $file, "<", "/file.txt") or die "cannot open < file.txt $!"; while (<$file>) { unless (/^A/) { print; } }
    That works, but I get the results of this script in the terminal. What I want is just to get these results to be saved in a new text file. Can somebody help me ? Please light my path amid the darkness with the wisdom that is yours Thanks a lot ! Chris
total noob question about xml parsing
4 direct replies — Read more / Contribute
by kgovert007
on Oct 25, 2014 at 10:59

    I am throwing myself at the mercy of the monks! I am seriously time-locked. I am just starting to learn Perl (old java programmer), but have just barely broken the seal on my "Perl in 24 hours" book. I am trying to figure out the simplest (not fastest or most efficient, just most maintainable) way to parse/manipulate some xml files. Here's the problem: I am working on a closed system that is locked down to perl-5.00503. Can anyone at least point me down the right path? I don't need an actual solution, (I wouldn't reject one, either -- I'm not stupid...) but I don't want to start off doing something that may have bad side-effects down the road.

    Thanks in advance to anyone who takes pity on me.
Sorting/Cleansing a Duplicate File
4 direct replies — Read more / Contribute
by perlron
on Oct 25, 2014 at 09:24
    With a desire to write elegant/optimal code in perl,i want to know any suggestions the monks might have to spare me.
    A customer gave me a word document with country (duplicates due to multiple commitees per country)names.
    I need to create a drop down in html showing country names. Hence my trivial code below to read a list of duplicate country names , identify unique names and write them to a file in alphabetical order. Basic stuff.
    #!/usr/bin/perl use strict; my ($key,$name,%countries); open (my $fh1,"<","files/country_listv1.txt") or die $!; while(<$fh1>){ if (!exists $countries{$_}){ $countries{$_} = '1'; } } open (my $fh2,">","files/country_listv2.txt") or die $!; foreach $key (sort keys %countries){ print $fh2 $key; } close($fh1,$fh2);

    Also if there is any glaring mistake pls let me know im getting back to perl after many years.. Even better, do we have some perl code checker available for us to validate scripts / modules ?
    Do not wait to strike when the iron is hot! Make it hot by striking - WB Yeats
remove non ascii characters in a whole corpus
3 direct replies — Read more / Contribute
by Anonymous Monk
on Oct 25, 2014 at 05:10

    I have a program that will remove all non ascii characters from a single file. However, what a need is a program that will remove all non acsii characters from over 400 separate files. And I need the new, clean files (still separate) in a new folder. Thanks.

File::Find duplicate question
3 direct replies — Read more / Contribute
by Anonymous Monk
on Oct 24, 2014 at 17:32
    Hi Monks I have this code (from here which was done for me, I'd log in but the system won't send me a new password) The question, does the code look correct for finding duplicate files, based on the output I'm getting it looks like it is checking size instead of name first? And if I may a second question, how do I output paths with the slash leaning the Windows way? The output is e.g. c:/Temp\testfolder I'm using the code through a C# GUI and the output needs to be \ for the whole path spat out.
    #!/usr/bin/perl -w use strict; use File::Find; # No warnings so the output doesn't state which folders it # can't access (Windows issue) no warnings 'File::Find'; use Digest::MD5; local $| = 1; #**************** File Scope Variables ********************* my $path = $ARGV[0]; my $testpath = 'C:/Temp/'; #*********************************************************** my %files; my $wasted = 0; print "Searching for duplicate files on $ARGV[0]\n"; find(\&check_file, $path); #find(\&check_file, $ARGV[0] || $usbstick); local $" = ","; foreach my $size (sort {$b <=> $a} keys %files) { next unless @{$files{$size}} > 1; my %md5; foreach my $file (@{$files{$size}}) { open(FILE, $file) or next; binmode(FILE); push @{$md5{Digest::MD5->new->addfile(*FILE)->hexdigest}},$file."\ +n"; } foreach my $hash (keys %md5) { next unless @{$md5{$hash}} > 1; print "\n@{$md5{$hash}}"; print "File size $size"; $wasted += $size * (@{$md5{$hash}} - 1); } } 1 while $wasted =~ s/^([-+]?\d+)(\d{3})/$1,$2/; print "\n$wasted bytes in duplicated files\n"; sub check_file { -f && push @{$files{(stat(_))[7]}}, $File::Find::name; }
Perl can't make some easy arithmetics :(
2 direct replies — Read more / Contribute
by rsFalse
on Oct 24, 2014 at 16:21
    Today I spend time to understand why do I get wrong answers, and I don't know an answer. Later I tried and found how to overcome problem: use bigint and add zeroes. See this:
    while(<>){ ($a, $b)=split/ /; print $a - $b, " "; print (($a+0)-($b+0), " "); use bigint; print $a - $b, " "; print (($a+0)-($b+0), "\n"); }
    STDIN: 9 7 900000000000000009 900000000000000007 STDOUT: 2 2 2 2 0 0 0 2
Making PDF Tables
2 direct replies — Read more / Contribute
by Anonymous Monk
on Oct 24, 2014 at 15:13
    Hi Monks!
    I need to create a PDF document with a few tables in it, from the code sample of the module PDF::Table its simple to have one table in the same page of a PDF, but I canít figure it out how I would add another table into the same PDF page. Has any of you tried or had to do the same thing using the same module?
    Code Sample
    use PDF::API2; use PDF::Table; my $pdftable = new PDF::Table; my $pdf = new PDF::API2(-file => "table_of_lorem.pdf"); my $page = $pdf->page; # some data to layout my $some_data =[ ["1 Lorem ipsum dolor", "Donec odio neque, faucibus vel", "consequat quis, tincidunt vel, felis."], ["Nulla euismod sem eget neque.", "Donec odio neque", "Sed eu velit."], #... and so on ]; $left_edge_of_table = 50; # build the table layout $pdftable->table( # required params $pdf, $page, $some_data, x => $left_edge_of_table, w => 495, start_y => 750, next_y => 700, start_h => 300, next_h => 500, # some optional params padding => 5, padding_right => 10, background_color_odd => "gray", background_color_even => "lightblue", #cell background color for +even rows ); # second table in the same PDF page $pdftable->table( # required params $pdf, $page, $some_data, x => $left_edge_of_table, w => 500, start_y => 755, next_y => 705, start_h => 305, next_h => 505, # some optional params padding => 5, padding_right => 10, background_color_odd => "navy", background_color_even => "red", #cell background color for even r +ows ); # do other stuff with $pdf $pdf->saveas();

    Thanks for looking!
compare always true in grep
5 direct replies — Read more / Contribute
by RonW
on Oct 24, 2014 at 14:05

    The following worked fine on Linux, but is not working on Win7 Pro (Strawberry Perl 5.18.2 64bit)

    (This uses the expression form of grep)

    #!perl -w use warnings; use strict; my @times = ( 1, 2, 3, 4); print STDERR "Times: @times\n"; if (grep ((0 + $_) >= 99999999), @times) { die('Time values must be < +99999999'); }


    >perl Times: 1 2 3 4 Time values must be < 99999999 at line 9. >
Mocked query returns wrong result
2 direct replies — Read more / Contribute
by Anonymous Monk
on Oct 24, 2014 at 10:37

    Hi perl monks

    I'm trying to mock an sql call (for practice purposes) using DBD::Mock and i'm getting a wrong result.


    #!use/local/bin/perl use Test::More qw (no_plan); use Data::Dumper; use DIR::DBTeams; use constant DB => "dbi::Mock:"; use constant DB_USER => "mock"; use constant DB_PWD => "mock"; my $db; my $query; my $columns; my @boundparams; my @results; my $test_teams; $query = q(select decode(substr(te.TEAM_ID,1,2),'MU','Manchester Unite +d', 'RM', 'Real Madrid')) from Teams t inner join TEAMS_EUROPE.TEAM_REF te + on t.TEAM_REF = te.TEAM_REF and t.TEAM_REF=:ref); $boundparams=('123'); #123 is reference for MU $columns=('TEAM_ID'); @results=('Manchester United'); $db = &connectDB(DB,DB_USER,DB_PWD); my $session = DBD::Mock::Session->new('my_sesion' => ( { statement => $query, bound_params = [@boundparams], results => [[$columns],[@results]] } ) ); $db->{mock_session}=$session; $test_teams = new DBTeams($db, $boundparams[0]); is($test_teams, "Manchester United", "Test Teams"); sub connectDB($$$) { my $dbh = DBI->connect($_[0],$_[1],$_[2]); return $dbh; }

    Code : DBTeams

    package DIR::DBTeams; use DBI; sub new { my $class = shift; my $self = {}; my ($dbh,$ref) = @_; $self->{dbh} = $dbh; &getTeam($ref); } sub getTeam { my $me = shift; my $ref = shift; my $ret; my $cur = $me->{dbh}->prepare( q(select decode(substr(te.TEAM_ID,1,2),'MU','Manchester United', 'RM', 'Real Madrid')) from Teams t inner join TEAMS_EUROPE.TEAM_REF te + on t.TEAM_REF = te.TEAM_REF and t.TEAM_REF=:ref)); $cur->bind_param(':ref',$ref); $cur->execute() or croak $cur->errstr; $ret = $cur->fetchrow_array(); $cur->finish; return $ret; }

    The code seems ok, but when it runs, instead of getting 'Manchester United', the method returns 1.

    I tried debugging and several alternatives and none seem to work.

    Finaly i tried changing the original code:

    Code : DBTeams

    ... ($ret) = $cur->fetchrow_array(); ...

    By placing $ret in ( ), the code now returns what i want. However, i want to know if there is an alternative that allows me to get the result i want without changing the original code.

    Can someone help me? Thanks

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 making s'mores by the fire in the courtyard of the Monastery: (7)
    As of 2014-10-26 04:54 GMT
    Find Nodes?
      Voting Booth?

      For retirement, I am banking on:

      Results (151 votes), past polls