Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
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
Want END block to run except when usage()/--help invocation
1 direct reply — Read more / Contribute
by CoVAX
on Feb 26, 2015 at 23:50

    This is the first time I've used an END block. I need its functionality because I call 'die' at several points throughout this program and I have to always perform the code in the END block.

    I was making the final edits to a program's usage() function and noticed the following warnings following a --help invocation:

    perl -w ks.pl -h
    Use of uninitialized value $time in concatenation (.) or string at ks. +pl line 253. Use of uninitialized value in concatenation (.) or string at ks.pl lin +e 258. Use of uninitialized value in concatenation (.) or string at ks.pl lin +e 258. Use of uninitialized value in concatenation (.) or string at ks.pl lin +e 258. Use of uninitialized value in concatenation (.) or string at ks.pl lin +e 258. Character in 'c' format wrapped in pack at ks.pl line 262. Use of uninitialized value $time in concatenation (.) or string at ks. +pl line 283.

    Ah so! (German for "I see!") -- these warnings were the result of the END block being (unconditionally) executed after the usage() function.

    While I understand why this is happening, my question is: is there a way to have an unconditional END block execute except when the program's usage() function is being invoked? If not, then I propose to create yet another function to be called prior to die()'ing that will execute what's presently in the END block.

    Here's the relevant code:

    #!/usr/bin/perl -w use strict; use Getopt::Std; ... # Don't want END block to execute when these are invoked: sub HELP_MESSAGE(); # getopts() --help automatically invokes VERSIO +N_MESSAGE() first sub VERSION_MESSAGE(); # getopts() supports arguments --version and -- +help sub usage(); ... INIT { $| = 1; # Make Getopt::Std exit after printing # VERSION_MESSAGE() and/or HELP_MESSAGE() $Getopt::Std::STANDARD_HELP_VERSION = 1; } ...By design, main-line code comes to this END block: # An END block is always executed (barring some exceptions) as # late as possible, even after die() is called END { export_to_file_csv(); export_to_storable(); warn "Pages : $pages of Total Pages: $total_pages"; warn "Projs : $projs of Total Projs: $total_projs"; warn sprintf ("Images: %d amounting to bytes: %s", $imgs, $bytes)); } # END OF PROGRAM (normal or otherwise).

    I thank you for your time and assistance.

    Searched for donut and crumpit. Found donate and stumbit instead.
Why did @$ variable bite me in the ass?
3 direct replies — Read more / Contribute
by dmitri
on Feb 26, 2015 at 14:12
    So there I was, happily rolling along, writing my class, and using an array ref as my underlying data structure. I then wrote another method:
    sub another_method { my ($self, $magic_val) = @_; $$[MAGIC_VALS]{$magic_val} = 1; }
    and ran it. There were no compile-time or run-time errors, but the logic did not work. Can you spot the problem? That's right: it should be $$self[MAGIC_VALS]{$magic_val} instead! What is this magical @$? Perl does not complain about it and will happily use this array:
    use strict; use warnings; $$[0] = 1; $$[1] = 'dude!'; print "@$", "\n"; # Prints "1 dude!"
    It's not in perlvar... What's up with this variable?
HELP: Problem with PDF
2 direct replies — Read more / Contribute
by cristofayre
on Feb 26, 2015 at 13:24
    I'm tearing my hair out!!

    I generated a PDF with AP12. If I click the file locally, it loads into reader fine. But no matter what I do in perl, it stops loading data at around 4K of a 212K file. (Reading the data sent to page in a text editor, it seems to stop at %%EOF)

    I have tried the usual "While(<xx>)" and "@file=<ZZ>", and even tried the "local $/" to set to undefined size ... but still it stops reading at 4K / %%EOF

    << /Info 4 0 R /Root 1 0 R /Size 815 >> startxref 207080 %%EOF

    So I can't even 'grab' it to send it to a zip file, (everything is code based from generating file to delivery) 'cos I can't read the entire file ... My ultimate aim is to get the file to the browser, or to a save prompt - but can't do either.

    Annoying thing is, I've got it to work before using the "Content-disposition" "content-type: application/pdf" ... but I suspect those files are less than the buffer size (??)

    I even tried it with another file (8MB) Whilst I got the correct number of pages after 20 seconds - and having to switch to an older reader ... there was no text on any page!!

    I can't even email it to people ... cos I can't read the entire file to memory.

    Final try:

    open (QR, "<QR_labels.pdf"); binmode(QR); print "Content-type: application/pdf\n\n"; print 'Content-Disposition', "attachment; filename=Booth_guide.pdf\n\n +"; while(read(QR,$buffer,10000)){ print $buffer; } close(QR);

    Same thing. Only 4K delivered to browser from 212K, and breaking as shown above. This has me beaten! I don't know what to try next

[OT] Stats problem
7 direct replies — Read more / Contribute
by BrowserUk
on Feb 26, 2015 at 04:47

    Any group of 4 bytes in memory can contain any of 2^32 values.

    4GB of memory contains 2^29 (1/2 a billion) 8-byte aligned, 4-byte fields.

    If a runaway loop writing random bytes overruns its buffer and scribbles over one of the 32-bit fields, what are the odds that the 4-bytes, viewed as an unsigned 32-bit integer, would match that fields offset into the 4GB of ram?

    Illustratively:

    memory:(hex)[00000000........][00000008........][00000010........][000 +00018........]...[12345678........][12345680........]... offset:(dec) 0 8 16 24 + ... 305419896

    The premise is that if free blocks are maintained with their offset into the 4GB block, and a buffer overun occurs, then any block that has been overwritten is easily detectable, with a high degree of certainty. A far higher degree than if the typical fixed known bit-pattern is written there.

    Corruption could write any of the possible values anywhere; and if a fixed bit-pattern is used as the marker, there is, assuming total random corruption, a 1 in 2^32 chance of a specific field being mistaken for the fixed bit pattern. But with potentially 2^29 fields, those odds reduce markedly. I think to 1:(2^32/2^29) = 1 in 8 chance if the whole 4GB were corrupted.

    But the odds that an exact offset value will be written at that exact offset has to be many time higher. But how high?


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
Is there an IO::*-like interface for accessing tar files?
2 direct replies — Read more / Contribute
by atcroft
on Feb 25, 2015 at 11:46

    Can anyone recommend a module that would provide an IO::*-like interface for accessing tar files?

    In a recent project at $work, I used IO::File and IO::Uncompress::AnyUncompress to simplify processing of compressed (bzip2 or gzip) or uncompressed files. (For example, reading lines via $foo->getline(), or current line number by $foo->input_line_number.) Now, I have been asked to add processing for tar archives. While I have used Archive::Tar for processing tar archives before, I was hoping that there might be module that could provide an IO::*-like interface so I could minimize the changes needed to add the support.

    Thank you for your time and attention, and any direction you may provide.

STDOUT msg routing
2 direct replies — Read more / Contribute
by sandy105
on Feb 25, 2015 at 05:11

    I have many legacy scripts which print logs directly to STDOUT and use a scheduler where they pipe the stdout to a log file >>alog.log ; however is there any way inside perl to force these msgs to print to a file rather than console

    --just wondering if its possible to do it

Name of caller if aliased?
3 direct replies — Read more / Contribute
by LanX
on Feb 24, 2015 at 23:15
    Precious Monkses!

    (caller(0))[3] shows me the name of the currently executed function.

    But in case of importing/aliasing it'll be the original one not the alias' name.

    Any way to find the name of the alias?

    details:

    $\="\n"; sub show { print join "\t",(caller(0))[0..3]; }; show(); *func = \&show; func();

    prints

    /usr/bin/perl -w /tmp/tst.pl main /tmp/tst.pl 6 main::show main /tmp/tst.pl 10 main::show

    any straight forward way to get "main::func" in the second case?

    (no, parsing the calling line is not an option)

    Thankses for your attention! :)

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

    PS: Je suis Charlie!

Spooky actions from a signal handler possible?
2 direct replies — Read more / Contribute
by belg4mit
on Feb 24, 2015 at 13:51
    Hello all, is there some way for code within a signal handler to affect the greater program? I found Setting up signal handlers for an object with access to $self, which has allowed me access to my data within the signal handler, but neither changes to the object nor the %ENVironment seem to persist. I suspect it's not possible, but am wondering if there's something I am overlooking.

    For those curious, the goal is to install a handler that will handle broken pipes elegantly and fail over to a fallback. $SIG{PIPE} = 'IGNORE' is insufficient, and wrapping the calls that work with the pipe in eval{} fails the elegance test… Cheers!

    UPDATE: In the end it turned out to be possible to get information out of the signal handler, but block eval was still required. However I hit upon a relatively elegant means of using it: Rather than wrapping multiple statements within eval. I decided to put everything in an eval block, and use it as a replacement for do in my control structure e.g;

    eval{ ... } while ($condition);

    --
    In Bob We Trust, All Others Bring Data.

simple awk feature in perl
4 direct replies — Read more / Contribute
by jasonwolf
on Feb 24, 2015 at 11:38

    I am currently working on a simple BASH script for a Nagios plug-in; however, BASH does not do floating point integer, so I wanted to use this time for Perl.

    BASH code

    poltx=$( snmpget -v 2c -c readonly 192.168.1.23 IF-MIB::ifInOctets.5001 | awk {'print $4'})

    I am able to wrap cli commands in `command`, so I can wrap commands; however, I am a little lost at the awk portion. I have reviewed a number of forums; however, I am still lost, and wanted to communicate with someone to ask questions on how I can do this as easiest possible, so I can learn at the same time.

    Thank you JW
Non-CGI perl scripts on a web server?
5 direct replies — Read more / Contribute
by Amblikai
on Feb 23, 2015 at 08:12

    So i may have this completely wrong and if so i apologise for the daft question! But...

    I'm no web developer but have a really basic web site that i'm messing around with. I write a lot of perl and i want a button on the website to execute a perl script.

    So far i've managed to so far get a hello_world.pl to execute. And so comes my question: The only way i could get it to work was by inserting the line: print "Content-type: text/html\n\n"; into the script

    What if the perl script is not generating any html or anything? Say it's just a script which accesses a mySQL database and writes a file or runs some kind of system command. Do i still need the print "Content-type: text/html\n\n"; Are there other types of "Content-type"

    Feel free to tell me to p*** off and do some more reading but my google-fu is clearly lacking and i might just need a nudge in the right direction. If you have any links, they'd be greatly appreciated!

    Thanks!

Spreadsheet::XLSX file reading problem
1 direct reply — Read more / Contribute
by gdg8
on Feb 22, 2015 at 09:43

    I have been using Spreadsheet::XLSX for a while with no problem but have now hit a problem with reading a large (10M) xlsx file. (Mac OS Yosemite)

    The error I get is

    IO error: opening MasterCopies/BigFile.xlsx for read : No such file or directory at /Library/Perl/5.18/Archive/Zip/Archive.pm line 563. Archive::Zip::Archive::read('Archive::Zip::Archive=HASH(0x7fcbea80 +7328)', 'MasterCopies/BigFile.xlsx\x{a}') called at /Library/Perl/5.1 +8/Spreadsheet/XLSX.pm line 33

    Any suggestions as to how to fix this? The size of the file may be irrelevant but can't see any other difference from previous successful usage.

Design thoughts: iterator invalidation
7 direct replies — Read more / Contribute
by BrowserUk
on Feb 20, 2015 at 10:35

    You employ a class that provides a hash-like interface designed for multi-threaded operation. A part of that interface is the provision of iterators. Whilst one thread is using an iterator, other threads may be modifying the data structure. Modifications might include any of:

    1. Modifying existing values;
    2. Adding new key/value pairs;

      Which in-turn might cause a resize operation.

    3. Deleting existing key/value pairs;
    4. Explicitly clearing all the key/value pairs.

      As opposed to implicitly because of going out of scope.

    It obviously becomes necessary to invalidate existing iterators when some of the modifications occur. But is it necessary for all of them?

    For example, with case A), if the only modification is the updating of a value; any existing iterator has either: a) already traversed that pair and retrieved the old value; or b) will traverse it sometime and get the new one. In other words, it will get a value which happens to be the current value at that moment in time and provided that the threads are properly decoupled (ie. not timing dependent) correct algorithms should be fine in either case.

    The other cases are less clear cut. One school of thought is that if a deletion or insertion occurs behind an existing iterator; then the affected key/value pair has already been processed, so it doesn't matter; and if it happens ahead of the existing iterator they'll get processes once the iterator gets there.

    The problem is that the nature of hash structures is such that an insertion or deletion either ahead or behind could affect the structure (eg. cause a rehash or resize) such that the iterator might now revisit pairs already processed and/or skip keys that haven't yet been. And what if the deletion deletes what would be the next pair to be returned. If the iterator returned undef -- what else could it do? -- then that would be confused with the normal iterator completed return.

    If another thread completely empties the hash; then it could be viewed that having existing iterators simply end is the right thing to do. But of course, for some algorithms that could result in false statistics, data or conclusions.

    So, the questions rattling around my brain are:

    • Under what circumstances should an iterator become 'invalidated'?
      1. When any change is made.
      2. When a key is inserted? Destroyed? Both?
      3. When the hash is resized (thus destroying the integrity of the iterator sequence)?
      4. Other?
    • Should this be user configurable?
    • How should an iterator signal that it is invalidated?
    • How to detect that an iterator needs to be invalidated?

    I've been thinking about this for a while and I'm beginning to suspect that there is no one right answer to it. What I'm looking for is some kind of feel for what might constitute a 'most cases' right answer.

    Thoughts?


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
    any
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 wandering the Monastery: (10)
As of 2015-02-27 13:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    On my keyboard, Caps lock is:








    Results (444 votes), past polls