Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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
Stupid question about strings...
2 direct replies — Read more / Contribute
by kepler
on Jul 14, 2014 at 04:10
    Hi, I'm having an annoying stupid and simple problem: I have a string equals to $str1 = "|L|D|"; and I want to know if string 2, $str2, is in $str1. I'm using the expression: if($str1 =~ /$str2/gi){... Why isn't it working? What am I doing wrong? This is stupid... Regards. Kepler
Not able to assign a hash reference.
1 direct reply — Read more / Contribute
by Ankur_kuls
on Jul 14, 2014 at 02:49

    Hi monks..I have this script which reads i/p file line by line into variable $p, manipulates in a way it becomes a hash reference.. but when I print the $p it prints the manipulated line not something like HASH(0x1e0e9b8) (means it isn't a hash ref. just a normal variable... below is my script..

    $line = "cksjdcdbsdcnusageControlAccum:S551(!{\!reportingGroups\!:[{\! +absoluteAccumulated\!:{\!counters\!:[{\!bidirVolume\!:306490319,\!nam +e\!:\!base\!}],\!expiryDate\!:{\!volume\!:\!24-07-2014T00:00:00\!},\! +previousExpiryDate\!:{\!time\!:\!26-06-2014T00:00:00\!,\!volume\!:\!2 +6-06-2014T00:00:00\!},\!reportingLevel\!:\!totalTraffic\!,\!resetPeri +od\!:{\!volume\!:\!28 days\!}},\!name\!:\!110\!,\!restartInfo\!:\!26- +06-2014T00:00:00\!,\!selected\!:\!yes\!,\!subscriberGroupName\!:\!GJ_ +FUP_3GEXP_125MB_28\!,\!subscriptionDate\!:\!26-06-2014T00:00:00\!,\!v +alidityTime\!:3600}],\!version\!:\!2.1\!}!)"; $line =~s/\\//g; if ( $line =~ /usageControlAccum:(\w+)\(!(.*)!\)/ ) { $p=$2; $p=~s/:\{/ => {/g; $p=~s/:\[/ => [/g; $p=~s/!/\'/g; $p=~s/\':/\'=>/g; } print $p;

    ouput of which is

    {'reportingGroups' => [{'absoluteAccumulated' => {'counters' => [{'bid +irVolume'=>306490319,'name'=>'base'}],'expiryDate' => {'volume'=>'24- +07-2014T00:00:00'},'previousExpiryDate' => {'time'=>'26-06-2014T00:00 +:00','volume'=>'26-06-2014T00:00:00'},'reportingLevel'=>'totalTraffic +','resetPeriod' => {'volume'=>'28 days'}},'name'=>'110','restartInfo' +=>'26-06-2014T00:00:00','selected'=>'yes','subscriberGroupName'=>'GJ_ +FUP_3GEXP_125MB_28','subscriptionDate'=>'26-06-2014T00:00:00','validi +tyTime'=>3600}],'version'=>'2.1'}

    now if I assign the above output value directly to any variable & then print is considering it like a hash ref but not in this case...pls help..thanks

To find the no of occurenaces and max min value
3 direct replies — Read more / Contribute
by Madhavan11
on Jul 14, 2014 at 02:47

    Please help me to find the no of occurrences in file. also to find the max and min values. Im able to find the no of occurrences.

    file =====
    SQL :: select * from person ...etc , Time Taken :: 30
    SQL :: select * from emp ...etc , Time Taken :: 5
    SQL :: select * from home ...etc , Time Taken :: 20
    SQL :: select * from emp ...etc , Time Taken :: 30
    SQL :: select * from person ...etc , Time Taken :: 10
    SQL :: select * from home ...etc , Time Taken :: 20
    SQL :: select * from person ...etc , Time Taken :: 50
    output should be =================
    SQL No of occu total Min Max
    select * from person 3 90 10 50
    select * from emp 2 35 5 30

Refactor this to eliminate the duplicated printf?
4 direct replies — Read more / Contribute
by wanna_code_perl
on Jul 13, 2014 at 23:48

    Here's a simplified version of a pattern I come across every so often that bugs me: you're reading from a stream of unknown length, you need to do "something" at every Nth iteration, and N is pretty much never an even divisor, so there are always leftovers, which makes for a clumsy re-use of the "something", like so:

    use 5.014; use warnings; my ($sum, $count) = (0,0); while (<DATA>) { $sum += $_; $count++; if ($count == 5) { printf "Sum: %4d, count: %2d, mean: %5.1f\n", $sum, $count, $sum/$count; $sum = 0; $count = 0; } } printf "Sum: %4d, count: %2d, mean: %5.1f\n", $sum, $count, $sum/$count; __DATA__ 61 23 30 444 368 438 467 44 812 430 992 469

    This outputs:

    Sum: 926, count: 5, mean: 185.2 Sum: 2191, count: 5, mean: 438.2 Final Sum: 1461, count: 2, mean: 730.5

    Often, the "something" (the printf in my example, but could be a few statements in length) doesn't warrant putting it into a sub (and paying the function call overhead every Nth time through the main loop), but neither do I like having to copy/paste it just to catch the leftovers after the loop exit.

    Is there a good way to refactor this so I don't have to repeat the printf, without sticking it in a sub?

A fast way to do this?
4 direct replies — Read more / Contribute
by Anonymous Monk
on Jul 13, 2014 at 19:30
    Hi Monks,
    I have an output file of a program, where I can have 2 possibilities:
    If I do not have any results that can be manipulated, all the lines of the output file will start with #, else, there will be some lines that will not start with #.
    I was wondering if there is a way, without maybe having to read every line in the file, to quickly see if there exist lines that do not start with # (which would mean that I can process this file further.
unique elements in a Hash of Arrays?
1 direct reply — Read more / Contribute
by Anonymous Monk
on Jul 13, 2014 at 14:37
    Dear Monks,
    can you please guide me on how to find the number of unique elements in a hash of arrays?
    I know that, if you have a normal array, you can just do:
    $unique_ids = scalar(grep {defined $_} @normal_array);

    but how can I do the same thing if there is a has of arrays involved? For example, how do you find the number of unique elements in the array for each of the keys in this example
    %HoA = ( flintstones => [ "fred", "barney","barney", "nick", "john", "barne +y" ], jetsons => [ "george", "jane", "elroy", "mike", "elias" ], simpsons => [ "homer", "marge", "bart", "jack", "homer" ], );
Problem computing GC content
2 direct replies — Read more / Contribute
by zuepinhel
on Jul 13, 2014 at 13:26

    Hey guys! I'm new to Perl, and on my first assignment i've been developing a program to calculate the GC content of DNA sequences on a txt file. The file has +10 sequences and i'm only getting the result of the last one. Is there some problem with the loops ? The code is as follows. Thanks!

    #!/usr/local/bin/perl open (FASTAFILE, 'human_fold_25.txt'); $sequence = ' '; $Ccount = 0; $Gcount = 0; $identifier = ' '; while ($line = <FASTAFILE>) { chomp $line; if ( $line =~ /^>/ ) { $identifier = $line; } elsif ( $line =~ /^\./ ) { next; } elsif ( $line =~ /^\(/ ) { }else { $sequence = $line; } } $sequencelength = length ($sequence); @nucleotides = split ( '' , $sequence ); foreach $nuc (@nucleotides) { if ( $nuc eq 'G') { $Gcount = $Gcount + 1; } elsif ( $nuc eq 'C') { $Ccount = $Ccount + 1; } } $GCcontent = ((( $Gcount + $Ccount )/ $sequencelength ) * 100); close (FASTAFILE); print "$identifier", ", ", "$GCcontent\n"
Help parsing badly constructed logfiles
2 direct replies — Read more / Contribute
by Amblikai
on Jul 13, 2014 at 12:07

    Hi folks, i spent the last day or so writing a quick logfile parser. It literally just searches the file for categories of search terms. I was happy with my new creation!


    I've just realised that when the logfile is created, newlines are being randomly inserted into the file. I've no idea why. It seems just to be the way these logs are created!

    The problem being that occasionally, my search terms are cut in half by a newline! How on earth am i supposed to deal with that?

    Any advice would be greatly appreciated. Thank you!

Perl tk entry widget to get arguments for perl script.
2 direct replies — Read more / Contribute
on Jul 13, 2014 at 09:28
    Hi, I have a script which via the command line asks the user for the the required Year,Month and Day and then processes a file with those details.
    #!/usr/bin/perl #use strict; use warnings; use Spreadsheet::WriteExcel; use File::Copy qw(copy); open(STDERR, ">&STDOUT"); #Set-up Files my $yyyy = $var[0]; print "Enter year in YYYY format:\n"; $yyyy = <STDIN>; chomp $yyyy; my $mmm = $var[1]; print "Enter Month in 3 letter abr format\njan,feb,mar,apr,may +,jun,jul,aug,sep,oct,nov,dec:\n"; $mmm = <STDIN>; chomp $mmm; my $dd = $var[2]; print "Enter day in number format\n01,02,03,04 etc:\n"; $dd = <STDIN>; chomp $dd; <\code> <p> How can i create and bind a Tk pop up entry widget for this, I have c +reated the browseEntry widget but need help on binding it to the vari +ables. <code> #!/usr/bin/perl use strict; use warnings; use Tk; use Tk::BrowseEntry; my $mw = MainWindow -> new; $mw->geometry("380x155"); $mw->title("Adhoc Failures"); my $browseEntryyear = $mw ->BrowseEntry( -label => 'Select year :', -relief => 'sunken', #-variable => \$var0, -state => 'readonly', -autolistwidth => '1', -justify => 'right', -buttontakefocus => 1, -relief => 'sunken') -> pack( -ipadx => 33, -side => 'top', -fill => 'x', -anchor => 'e', -expand => 1); $browseEntryyear -> insert('end', qw(2013 2014 2015 2016 2017 +2018 2019 2020)); my $browseEntrymonth = $mw ->BrowseEntry( -label => 'Select Month :', #-variable => \$var1, -state => 'readonly', -autolistwidth => '1', -justify => 'right', -buttontakefocus => 1, -relief => 'sunken') -> pack( -ipadx => 33, -side => 'top', -fill => 'x', -anchor => 'e', -expand => 1); $browseEntrymonth -> insert('end', qw(Jan Feb Mar Apr May Jun +Jul Aug Sep Oct Nov Dec)); my $browseEntryday = $mw ->BrowseEntry( -label => 'Select Day :', #-variable => \$var2, -state => 'readonly', -autolistwidth => '1', -justify => 'right', -buttontakefocus => 1, -relief => 'sunken') -> pack( -ipadx => 33, -side => 'top', -fill => 'x', -anchor => 'e', -expand => 1); $browseEntryday -> insert('end', qw(01 02 03 04 05 06 07 08 09 + 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31) +); my $but = $mw -> Button(-text => " Enter ", -command =>\&push_button, -relief => 'raised')->pack(-side + => "bottom",-fill => 'x'); MainLoop; #sub push_button { yourFunc($var0,$var1,$var2) };
input special characters
2 direct replies — Read more / Contribute
by kepler
on Jul 13, 2014 at 06:17
    Hi, I'm having this problem: I'm trying to input a character that will be used to separate fields for an output to a file. Example: if I input | the result string in the file will be: Field1|field2| etc... But how can I insert a special character like \t? I'm only getting: Field1\tField2\t etc... instead of the fields be separated by tabs. Is there a way to solve this? Regards, Kepler

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 lurking in the Monastery: (11)
    As of 2014-07-14 08:38 GMT
    Find Nodes?
      Voting Booth?

      When choosing user names for websites, I prefer to use:

      Results (257 votes), past polls