Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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
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
    Hi,

    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 foo.pl for testing purposes in the directory C:\MyDir:
    print "bar\n";

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

    As noted above, I would like to start foo.pl by
    C:\>perl foo.pl
    ------
    I carefully readed http://perldoc.perl.org/perlrun.html and found the switch -S, which includes the path environment variable for searching. So
    C:\>perl -S foo.pl
    Works
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: http://search.cpan.org/~szabgab/Parallel-ForkManager-1.06/lib/Parallel/ForkManager.pm

    use Parallel::ForkManager; ... @links=( ["http://www.foo.bar/rulez.data","rulez_data.txt"], ["http://new.host/more_data.doc","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);


    $searchSQL->execute();
    while (my ($id,$name) = $searchSQL->fetchrow_array()) {
    $insertSQL->execute($id,$name);
    $insertSQL->finish;
    }


    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?

    Thanks
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 (http://www.snowelm.com/~t/doc/tips/simple-proxy.en.html). 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,

    Ivan

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 }
Looping in a Loop
5 direct replies — Read more / Contribute
by Violet
on Sep 16, 2014 at 08:42

    I am completely new to Perl and would like some feedback/assistance. Hoping I don't make anyone cringe too badly.

    Trying to open a list and use each item on the list to bring out information on that item from the open file. Items will be listed in the second column of the file, but if the item matches I need to print all columns for that file.

    When I list all the items out directly in my code instead of opening the list, the code works. However, when I add the element of opening the list, I get no readout whatsoever.

    There are no warnings, so I can't figure out what's wrong. The format of my list maybe?

    #! C:\Perl\bin\perl -w open (LIST, "List.txt" ); @mylist = (<LIST>); open (FILE, "FILE.txt" ); @myfile = (<FILE>); foreach $file(@myfile) { foreach $list(@mylist) { @temp = split (/\t/, $file); chomp @temp; if ( $temp[1] eq $list ) {print ("$file")} } }
How to push the first two elements of an array in another array
3 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 16, 2014 at 05:25
    Hey Monks, I have a simple question, i really do not know, how to write it down. I have an Array
    @array1 = (1,2,3,4,5);
    and I want the first two elements (1 and 2) use in another Array.
    @array2 = (1,2);
    How do I do this? With grep? With splice? with push?? Thanks for your help
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2014-09-23 06:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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











    Results (210 votes), past polls