Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
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
Turning on regexp debugging at runtime
1 direct reply — Read more / Contribute
by SBECK
on Sep 23, 2014 at 10:55

    When tracking down a tricky regexp related problem, it's nice to turn on regexp debugging:

    use re 'debug';

    Ideally, I would like to be able to toggle it on and off (especially in the debugger) because there may be a lot of other regexp matching going on that works perfectly well, and I want to get to the portion that is broken. Unfortunately, I haven't figured out how to do that.

    I know this comes down to me not truly understanding how pragmas work, and maybe it's not possible, but is there a way to toggle debugging during runtime?

Where is $# fully documented?
5 direct replies — Read more / Contribute
by LanX
on Sep 23, 2014 at 10:08
    Hi

    I'm struggling to find the perldocs where the usage of $# (i.e. last-index) with array-references (not symbols) is documented. Can you help me?

    If not, what's the best place to augment the perldocs?

    Tested behavior (5.10):

    DB<107> @a = (1..5) # @array => (1, 2, 3, 4, 5) DB<108> $#a # classic usage => 4 DB<109> $a = [1..10] # arrref => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] DB<110> $#$a => 9 DB<111> $a = [ map [0..$_],0..3 ] # AoA => [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]] DB<112> $#{ $a->[2] } => 2

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

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
    @a1 = qw (ID1 len1 dom1 domlen1 seq1); @a2 = qw (ID2 len2 dom2 domlen2 seq2); @a3 = qw (ID3 len3 dom3 domlen3 seq3); $line1 = /@a1; $line2 = /@a2; $line3 = /@a3; @array =qw ($line1 $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 : http://www.perlmonks.org/?node_id=674374 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:

    ascii
    ascii-ctrl
    iso-8859-1
    null
    utf-8-strict
    utf8
    

    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
    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!
New Meditations
SNTP Client/Server V2 RFC
1 direct reply — Read more / Contribute
by thanos1983
on Sep 23, 2014 at 10:38

    Hello Monks,

    A few days ago, I finished my task on creating a running SNTP Client/Server. I had a similar post on my previous version UDP SNTP Client/Server RFC where I was introduced to the idea that this could be submitted as module on CPAN since nothing similar exists. The closest module that I could found is Net::NTP. Which in reality there are nothing to look a like to each other. The other module fetches and displays data from the NTP Server. The module that I propose is using the local clock of the server to calculate the roundtrip delay d and local clock offset t.

    So I thought if people are interesting in running a script like that it should have higher accuracy and actually support most if not all features of Simple Network Time Protocol (SNTP).

    Accuracy down to microseconds can only be achieved on Linux OS and not to Windows OS Time::HiRes not that high on windows.

    I would like to ask for possible improvements or suggestions of my code. Please take in consideration that I am not expert on programming and this is my first module submission.

    Also can Windows and MAC users test the code and provide feedback on the script execution. I mean if you have any problems or possible faults. I have developed the scripts on Linux so it is only tested on Linux environment.

    Update: client.pl and server.pl include use POSIX qw(CLOCKS_PER_SEC); for compatibility reasons with Windows OS. Thanks to the help of VinsWorldcom for the proposed solution.

    Client.pl

    Server.pl

    Possible future improvement is to apply threading on the server so it can reply on my multiple requests (clients) simultaneously.

    Thank you all for your time and effort to review and comment on my request.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
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 contemplating the Monastery: (3)
As of 2014-09-24 04:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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











    Results (245 votes), past polls