Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

The Monastery Gates

( #131=superdoc: print w/ replies, xml ) Need Help??

Donations gladly accepted

If you're new here please read PerlMonks FAQ
and Create a new user.

New Questions
sorting array of array references with multiple dereferenced array elements
3 direct replies — Read more / Contribute
by onlyIDleft
on Sep 23, 2014 at 08:07
    my @a1 = qw ($ID1, $len1, $dom1, $domlen1, $seq1); my @a2 = qw ($ID2, $len2, $dom2, $domlen2, $seq2); my @a3 = qw ($ID3, $len3, $dom3, $domlen3, $seq3); $line1 = /@a1; $line2 = /@a2; $line3 = /@a3; my @array =qw ($line, $line2, $line3); # an array of array references.

    I want to first sort @array by element 1 of @a1, @a2, @a3 i.e. $ID , then by element 2 - $dom, then by element 3 - $domlen, by element 4 - $seq (which would be an alphabetical sort) and finally by element [0] - $ID (another alphabetical sort).

    After this sort, I want to extract the 1st element - "ID" from 1st de-referenced array, in @sorted_array

    I tried something on the lines of the suggestion at : by jettero, but get an error message - I suppose because what I am trying is to sort by elements in the deferenced array of arrays- which is not what the post here is talking about, right?

    Thank you in advance!

    PS. Sorry about the long post title

Encode - List ALL available encodings [SOLVED]
1 direct reply — Read more / Contribute
by kzwix
on Sep 23, 2014 at 04:15

    Greetings, O wise ones.

    I would like to get a list of all the available encodings installed on my machine. The Encode documentation (on the Perl website) clearly states:

    To get a list of all available encodings including those that have not yet been loaded, say:
        @all_encodings = Encode->encodings(":all");

    Now, executing this command and displaying the list contents, one result per row, gives me the following result:


    However, when I type, in the very same program:

    my $canon = resolve_alias('Latin-9');
    print $canon ? "Found Alias for: $canon\n" : "Unknown\n";

    I get the result:

    Found Alias for: ISO-8859-15

    Now, this leaves me puzzled: The canonical name clearly wasn't stated in the list which was supposed to give me all available encodings... I have the same problem with other encodings, too.

    Would you know what I do wrong ?

Finding Minimum Value
8 direct replies — Read more / Contribute
by jimmy88
on Sep 21, 2014 at 19:03

    Please forgive me for my naivety but I'm having an issue that I'm sure one of the wise perl monks can quickly resolve: My script processes all of my input data as desired with the exception of minimum values for the input grades. What is the issue here and how can I ensure accurate output? Once again, sorry to bother by asking for help with something so seemingly simple. Your help is much appreciated.

    ***students.txt*** 122334:James,Lebron: 222223:Duncan,Tim: 244668:Bryant,Kobe: 355779:Durant,Kevin: ****************** ***grades.txt*** 122334 1 98 222223 1 86 244668 1 89 355779 1 90 122334 2 96 222223 2 88 244668 2 92 355779 2 96 122334 3 97 222223 3 96 244668 3 95 355779 3 94 122334 4 97 222223 4 96 244668 4 95 355779 4 94 122334 5 97 222223 5 96 244668 5 95 355779 5 94 **************** #!/usr/local/bin/perl #Assign class roster file to variable. $students = 'students.txt'; # Open class roster. open (NAMES, "<$students") || die "Couldn't open $students $!"; # Create and populate arrays. while (<NAMES>) { ($id,$name) = split(':',$_); $name{$id} = $name; # Monitor name length for purpose of print formatting. if (length($name)>$longestname) { $longestname = length($name); } # Creat group size variable for later use with class avera +ges. $groupsize = $.; } # Arrays are complete. Close file. close NAMES; # Assign grade spreadsheet to variable. $grades = 'grades.txt'; # Open grade spreadsheet. open (GRADES,"<$grades") || die "Couldn't open $grades $!"; # Create, populate and assign arrays. while (<GRADES>) { ($id,$exam,$grade) = split; $grade{$id,$exam} = $grade; # Monitor exam counter. if ($exam > $lastexam) { $lastexam = $exam; } } # Arrays are complete. Close file. close GRADES; # Create, format and print table headings. printf "%6s %-${longestname}s ", 'ID#','Name'; foreach $exam (1..$lastexam) { printf "%4d",$exam; } printf "%10s",'Total'; printf "%8s",'Avg'; printf "%8s",'Min'; printf "%8s\n\n",'Max'; # Define alphabetical sort subroutine. sub alpha { $name{$a} cmp $name{$b} } # Print formatted student data. foreach $id ( sort alpha keys(%name) ) { printf "%6d %-${longestname}s ", $id,$name{$id}; # Set total point counter to zero. $total = 0; foreach $exam (1..$lastexam) { printf "%4s",$grade{$id,$exam}; # Counter increment. $total += $grade{$id,$exam}; $examtot{$exam} += $grade{$id,$exam}; # Calculate minimum grades. if ($grade{$id,$exam} < $mingrade) { $mingrade = $grade{$id,$exam}; } # Calculate maximum grades. if ($grade{$id,$exam} > $maxgrade) { $maxgrade = $grade{$id,$exam}; } } # Print student's point total. printf "%10d",$total; # Print student's average. printf "%8d",$total / $exam; # Print student's minimum exam grade. printf "%8d", $mingrade; # Print student's maximum exam grade. printf "%8d\n", $maxgrade; } # Print heading for class averages. printf "\n%6s %${longestname}s ",'',"Average: "; # Calculate and print class averages. foreach $exam (1..$lastexam) { printf "%4d",$examtot{$exam} / $groupsize; } # Exit script. exit(0);
Where does perl looks for perl skripts [Answered]
3 direct replies — Read more / Contribute
by BluePerl
on Sep 20, 2014 at 14:54

    I found, that perl only looks in
    * the actual directory, or
    * in the path which I provided for the script

    Is it possible to provide something like a PATH environment variable, which tells perl where to look for *.pl skripts?

    I created for testing purposes in the directory C:\MyDir:
    print "bar\n";

    And tested here:
    C:\MyDir>perl bar C:\MyDir>cd .. C:\>perl Can't open perl script "": No such file or directory C:\>perl -I C:\MyDir Can't open perl script "": No such file or directory C:\>set PATH=%PATH%;C:\MyDir C:\>perl Can't open perl script "": No such file or directory C:\>perl C:\MyDir\ bar

    As noted above, I would like to start by
    I carefully readed and found the switch -S, which includes the path environment variable for searching. So
    C:\>perl -S
Parallel::ForkManager and CPU usage?
5 direct replies — Read more / Contribute
by janmartin
on Sep 19, 2014 at 11:00

    This is about Parallel::ForkManager on 64 bit strawberryperl.

    I need to process 1000s of images. Each totally independent of the others.

    Processing has CPU intensive parts, and parts that hardly use the CPU, but the GPU instead. The hardware has 8 cores, so I think of 8 processes? Each process to start multi-thread programs.

    Each image is of different size, and I know the processing time is different according to it. Therefore processes should run a different length.

    If a process is finished, a new process should start. To always have 8 processes.

    This should level the CPU usage after a few rounds due to the different time each process runs. But it doesn't.

    Looking at the Windows 8 Resource Monitor I see that all 8 processes run perfectly synchronized even after a long time.

    It looks like 8 process are started, then only after all 8 are finished 8 new processes are started?

    Code is straight from:

    use Parallel::ForkManager; ... @links=( ["","rulez_data.txt"], ["","more_data.doc"], ... ); ... # Max 30 processes for parallel download my $pm = Parallel::ForkManager->new(30); foreach my $linkarray (@links) { $pm->start and next; # do the fork my ($link,$fn) = @$linkarray; warn "Cannot get $fn from $link" if getstore($link,$fn) != RC_OK; $pm->finish; # do the exit in the child process } $pm->wait_all_children;
read CSV file line by line and create hash table
3 direct replies — Read more / Contribute
by lshokri02
on Sep 19, 2014 at 10:53

    This is my first time writing perl and I want to take a CSV file which looks similar to this:

    mask No. , block, size, base addr (hex), end addr (hex)--about 20 h +eader names fpg23, b002, 16384, 60000, 63FFF fpg23, b002, 16384, 800000, 803FFF fpg23, b003, 0, F00000, F00000 fpg23, b003, 4, F00000, F00004 fpg23, b003, 8, F00000, F00008 --so on for a variable amount of lines

    so each line is represented as its own block, but I want to be able after reading the file, to sort the file by base address and be able to access other information in its line such as the end addr. my coworker said to use hashes, so I'm thinking of a multidimensional hash. I'm thinking that the column names are the keys of the hash, so can I sort a specific key (aka Base addr. (hex) key? this is my current code, from what I understand it is making the column name keys and it is reading line by line, but those values, are they private to that while loop? I believe I have to incorporate them in my hash table that I'm calling %reghash, just unclear of how to do that. I'd appreciate any help/feedback. Thank you!

    #!/usr/bin/env perl use strict; use warnings; use diagnostics; use Text::CSV_XS; my $filename = 'test1.csv'; my %reghash; open(my $fh, '<', $filename) or die "Can't open $filename: $!"; my $csv = Text::CSV_XS->new ({ binary => 1, #allow special character. always set this auto_diag => 1, #report irregularities immediately }); $csv->column_names ($csv->getline ($fh)); #use header while (my $row = $csv->getline_hr ($fh)){ printf "Base Address: %s\n", $row->{"Base Addr. (Hex)"}; } close $fh;
fetchrow_array loop in perl 5.10
6 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 18, 2014 at 03:06
    We recently upgraded perl from 5.8 to 5.10

    we discovered after the upgrade that the fetchrow_array loop ends abruptly

    code snippet:
    my $searchSQL = $dbh->prepare($sql1);
    my $insertSQL = $dbh->prepare($sql2);

    while (my ($id,$name) = $searchSQL->fetchrow_array()) {

    if I comment out the "$insertSQL->execute($id,$name);" it loops thru all the records.

    the code perfectly works in 5.8 but not in 5.10

    any ideas?

Perl HTTP proxy experts
2 direct replies — Read more / Contribute
by gregaiken
on Sep 17, 2014 at 14:20

    I recently discovered Makino Takaki's boilerplade Perl proxy program ( I found this code to be relatively straight forward to use for the purpose of better understanding this mechanism and to experiment with.

    i've added a few lines of my own code to this boilerplate program, and am having trouble getting...

    $c->send_redirect("file:///C:/http_proxy_server/log.html", 303)

    to work as I'm wanting it to work. according to documentation, above command redirects the client to a new url, and the HTTP header code set to (in this case) 303 (meaning 'See Other'). when my Perl proxy is running, I am wanting to use it in a fun way (where I can send it 'commands' - encoded as URL get requests).

    with my web browser viewing a local file 'log.html' file (which contains many HTML forms). When I click one particular form, the form sends a get request like this 'http://proxycommand.code?function=AppendNewRecordToLogHtmlFile&newrecord=helloworld' to my Perl proxy server.

    my proxy program can then search the requested URL to see if it contains 'proxycommand.code'. if so, it then parses the GET query string to discover the special function I want my proxy to execute. In this case, the special function is to append a new record to the 'log.html' file, where the new record is 'hello world'.

    in my code, im able to successfully append the new record to 'log.html'. i sleep for a few seconds. i then send the above Perl command to tell the browser to redisplay the newly modified 'log.html' file

    in the chrome web browser, the browser itself is satisfied that its received a wellformed HTTP reply, the address field of the browser does reflect the newly requested local file. but since the browser was previosly viewing the exact same file (prior to my clicking the form submit button) - perhaps some caching mechanism is preventing the browser from showing the newly added record at the bottom of the 'log.html' file. if i manually click the chrome browsers 'refresh' button - this causes the appended new record to display in the browser.

    does anyone know why the browser is not displaying the newest version of the 'log.html' file? is this due to browser caching issues? if so, what is the solution? I would think this LWP-UserAGent module would automatically include a newer HTTP 'Date' header, but maybe its not, and i need to manually set this header myself? One website suggested setting a NON-standard HTTP header, 'Refresh: 1' which supposedly is used by most browsers but not an official part of RFC2616.

    any help here would be appreciated, as i'm a little confused

Gmail Send problem
2 direct replies — Read more / Contribute
by IvanH
on Sep 17, 2014 at 12:24

    Hello Monks,

    I am using Email::Send::SMTP::Gmail to send a newsletter. I set up a loop to send it to about 150 addresses. I know that the first few went successfully and the last few did not, so I suspect my coding to detect an error in the send is incorrect. I have been told that $mail will return -1 if it fails and therefore used the following code: Have I set this up correctly?

    $mail->send(-to=>"$email", -subject=>"$subject", -body=>"$emailtext",-contenttype=>'text/html'); if ($mail == -1) { die "Mail send error: $!\n"; } else { print "Success!\n\n"; print OUTFILE "Success!\n\n"; }

    Thanks for any help,


How to compare two dates?
4 direct replies — Read more / Contribute
by CountOne
on Sep 17, 2014 at 11:38
    Hi Monks, I am new to Perl and was wondering how to compare two dates in MM/DD/YYYY format. For example, if a date in column B is equal to or comes before the date in column A, return 1, otherwise return 0. How would DateTime be used for this range? Thank you for the help!
Spreadsheet::XSLX parsing workbook, but not retrieving values from cells
3 direct replies — Read more / Contribute
by divyahk
on Sep 17, 2014 at 06:35

    Hello, I am a newbie to Perl and have a problem with parsing an Excel file. I am using Spreadsheet::XLSX for reading data from an Excel file and extract each row of data, one row at a time. The code (partial) is as follows:

    use strict; use warnings; use Spreadsheet::Read; use Data::Dumper; my $excel = Spreadsheet::XLSX->new (‘xyz.xlsx'); if (!defined $excel) { die "Error: " . $excel->error() . "\n"; } print “Read with Spreadsheet::XSLX\n"; print Dumper($excel) . “\n";

    The output here shows that it’s reading the correct workbook as it can recognise the correct worksheet called “Paper.1”, and I think I am using the correct version of the Excel parser as it is indeed the .xlsx variety of Excel. Why are the cells not being read then? (As shown by cells =>undef)

    Read with Spreadsheet::XLSX : $VAR1 = bless( { 'Worksheet' => [ bless( { 'DefColWidth' => '8.43', 'MinCol' => 0, 'MaxRow' => 0, 'MinRow' => 0, 'path' => 'worksheets/sheet +1.xml', 'MaxCol' => 0, 'Name' => 'Paper.1', 'Cells' => undef }, 'Spreadsheet::ParseExcel:: +Worksheet' ) ], 'Flg1904' => 0, 'FmtClass' => bless( {}, 'Spreadsheet::XLSX::Fmt2007' + ), 'SheetCount' => 1 }, 'Spreadsheet::ParseExcel::Workbook' );
Problem creating animated GIF using GD and GD::Graph
2 direct replies — Read more / Contribute
by realityczar
on Sep 16, 2014 at 10:29
    Hi, Monks-

    I am trying to create an animated GIF of graphs using GD and GD::Graph. The following code creates individual graph GIF files, but the image.gif that results and is supposed to be the animated version won't open. Where have I gone wrong?

    Update: I searched the archives. I read them. And I didn't apply the wisdom. It's a lack of binmode. Sorry to have bothered you.

    use strict; use warnings; use GD; use GD::Graph::bars; my $img_width = 288; my $img_height = 216; my $number_of_hours = 24; my $img = GD::Image->new($img_width, $img_height); my $gifdata = $img->gifanimbegin(1,0); foreach my $hour (0..$number_of_hours-1) { my @h = CreateHistogram($hour); my @labels = 0..79; my @data = (\@labels, \@h); my $graph = GD::Graph::bars->new($img_width,$img_height); $graph->set( title => "HISTOGRAM HOUR $hour" ); my $gd = $graph->plot(\@data); $gifdata .= $gd->gifanimadd; open(FIL, ">image_$hour.gif"); binmode FIL; print FIL $gd->gif; close FIL; } $gifdata .= $img->gifanimend; open(GIF,">image.gif"); print GIF $gifdata; close GIF; exit; sub CreateHistogram { # stuff to create a histogram }
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 studying the Monastery: (15)
As of 2014-09-23 13:50 GMT
Find Nodes?
    Voting Booth?

    How do you remember the number of days in each month?

    Results (222 votes), past polls