Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
Do you know where your variables are?

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
Using Win32::SerialPort on Win7-64bit under 64-bit Strawberry Perl
2 direct replies — Read more / Contribute
by gri6507
on Apr 24, 2014 at 16:39
    Hello Monks,

    I recently has the pleasure of having my old computer upgraded for me to a Win7-64 bit. I put the 64-bit Strawberry Perl on that machine and tried to install the Win32::SerialPort module so that I could run one of my old scripts. However, the installation did not work, failing on a number of tests.

    This leads me to my questions:

    • Should I even be able to run a 32-bit module for serial port communication on a 64-bit machine with a 64-bit perl?
    • If I used a 32-bit Strawberry Perl instead, would I be able to run the 32-bit module, even though I am on a 64-bit machine?
    • Is there some other SerialPort module that I should be using instead? (I've tried to install Device::Serial, but that failed to even run because it tries to configure with a *NIX ./configure script)
    Your wisdom is appreciated.
Best way to remove elem of for loop
5 direct replies — Read more / Contribute
by HarryPutnam
on Apr 24, 2014 at 10:32
    Probably almost too basic but here is my query:

    I just want to know if there is a better way to remove elements of a for loop than the way I've been using. Perhaps there are unknown dangers to my method.

    Imagine a for loop sifting thru an array of directories, testing them for 'directorieness'.

    @ar contains a group of directories by there absolute file names.

    for (@ar){ if ( !-d $_){ print "<$_> cannot be found ... removing from list\n"; $_ = ''; } }

    If any are found, @ar will register it if processed.

    Is that a good way to do it?

Messing with %INC.
4 direct replies — Read more / Contribute
by Theodore
on Apr 24, 2014 at 09:03
    I have seen in Use of %INC ? the answer probably never, and if you do, just for read access to the question when %INC should be used. But I have messed with %INC and I would like to know if there is a better way to do the same thing.

    I wanted to be able to redefine a subroutine without restarting the main program process. The subroutine is in a separate .pl file and this specific file is changed: I want to redefine the subroutine with the new file contents without stopping and restarting the main process. In the case of compilation errors in, the main program should not die.

    Here is some demo code:

    The subroutine file (

    sub mysub { print "foo\n"; }; 1;
    The main program:
    #!/usr/bin/perl use strict; my $fn = './'; require $fn; while (<STDIN>) { chomp; my $in = $_; if ($in eq 'load') { delete $INC{ $fn }; my $code = "require '$fn'"; eval $code; if ($@) { print "ERROR! Keeping old code.\n"; } else { print "mysub replaced.\n"; }; }; &mysub(); }; exit 0;
    Run the main program. Pressing enter, prints "foo". Now, without stopping the main program, change the print statement in to print "bar". Enter 'load' in the main program. After "mysub replaced", "bar" should be printed.

    If you omit the delete $INC{ $fn }; line, the subroutine as expected is not redefined. Am I doing something wrong here? Is there a more "mainstream" way to achieve the same thing?

    Update: The answer is here: Re: Messing with %INC.
regex backtracking question
3 direct replies — Read more / Contribute
by aeqr
on Apr 23, 2014 at 20:29
    I have learned today that you could force the regex engine to fail and backtrack, for example with this:
    "ABCDEF" =~ /([A-Z]{3})(?{print "$1\n"})(?!)/;
    trizen explained to me how this regex worked and this is what I understood:

    First it matches ABC, then prints it, then fail, then backtracks to the position where the last match occured + 1.

    Then when it runs again, it will match BCD this time. Thus this loop prints:


    However based on this reasoning, I struggle to understand the next example:

    "ABCDEF" =~ /(\w{2,}?)(?{print "$1\n"})(?!)/;
    Here it matches AB first then prints it, then fails then backtracks. But here, instead of matching BC as I would expect it, it matches ABC. So after failing, it does not backtrack to pos+1 like in the previous example. And the loop prints:
    Can someone explain me what is wrong in my assumption?
Package declaration in code block
2 direct replies — Read more / Contribute
by McA
on Apr 23, 2014 at 11:46

    Hi all,

    more and more I see code examples of the following form:

    { package Modul; use This; use That; ... }

    What is the difference to the form of

    package Modul1; use This; use That;

    without being wrapped into a block?

    Can someone enlight me, please?

    Best regards

Dynamically adding methods to Moo class
1 direct reply — Read more / Contribute
by McA
on Apr 23, 2014 at 11:24

    Hi all,

    I'm writing a Moo based class with several methods. I'm pretty new to Moo. While writing the methods I saw that the bodies of the methods are almost the same. Is there a recommended way to "generate" these methods with Moo? Is there a kind of method generation facility? Or do I have to tweak with the symbol table?

    Thank you in advance.

    Best regards

Using the Math::BigFloat->digit() method
4 direct replies — Read more / Contribute
by Athanasius
on Apr 22, 2014 at 23:51

    I’m using the Math::BigFloat module, and noticed in the documentation’s Synopsis that it has a digit() method:

    $x->digit($n); # return the nth digit, counting from right $x->digit(-$n); # return the nth digit, counting from left

    But I can’t seem to get it to work:

    13:45 >perl -MMath::BigFloat -wE "my $n = Math::BigFloat->new(123); sa +y $n; say $n->digit(-1);" 123 Can't use an undefined value as an ARRAY reference at C:/Perl/Strawber +ry/strawberry-perl- +pm line 1209. 13:45 >p5u v Math::BigFloat Math::BigFloat C:\Perl\Strawberry\strawberry-perl-\per +l\lib\Math\ 1.998 13:46 >

    What am I doing wrong?

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Running blocks of shell script from within perl script
6 direct replies — Read more / Contribute
by lilgreen
on Apr 22, 2014 at 14:39

    I have a hash (%check) with the following content:

    'DESCRIPTION' => 'Checks that various system filesystems are at the mi +nimum size' 'NAME' => 'filesys_sizes' 'TIP' => '(/<filesystem> is less than XGB, increase FS size to minimum +) The /tmp filesystems has a minimum filesystem size of 1GB Increase the filesystem to a minimum of 1GB chfs -a size=2097152 /tmp' 'TIP_NUMBER' => 37 'CHECK_CODE' => ‘#!/usr/bin/ksh93 typeset -A SIZE_MIN SIZE_MIN=([/var]=2097152 [/tmp]=1048576 [/home]=1048576) ISHACMP=$(lslpp -Lqc cluster.*.server.rte 2>/dev/null | grep -c cluste +r) for fs in ${!SIZE_MIN[*]}; do fssize=$(df -k $fs | grep -v Filesystem | awk \'{print $2}\') if (( $fssize < ${SIZE_MIN[$fs]} )); then print "BAD;$fs is less than minimum size ($SIZE_MIN[$fs]}), in +crease to minimum size" elif (( $fssize == ${SIZE_MIN[$fs]} )); then print "GOOD;$fs is at minimum size (${SIZE_MIN[$fs]} kb)" else print "GOOD;$fs is greater ($fssize) than minimum (${SIZE_MIN[ +$fs]})" fi done'

    Here's the subroutine that's actually running the CHECK_CODE element:

    sub exec_check { my (%check) = @_; my @return = `$check{'CHECK_CODE'}`; foreach (@return) { my ($status, $string) = split(";", $_); print "$status $string"; } }

    I want to execute $data{'CHECK_CODE'} as a "chunk" - whatever is in it is run as a whole, and the perl script just handles the data returned from the chunk. I've tried and backticks and qx// and IPC::Run, and even open() but they all seem to have the same limitation - when I pass the hash element as the command to be executed it gets interpreted one line at a time. I always get the same error:

    sh[3]: typeset: 0403-010 A specified flag is not valid for this comman +d.

    On the system this being run on (AIX) this is a valid error for ksh because it doesn't have a -A option for typeset, but ksh93 does support -A so it's clear that each line of the code is being interpreted as a new child process. I've been fiddling with it for a while and am currently at the banging-my-head-against-the-wall phase, because I'm sure there's something completely obvious that I'm missing. It seems like it should be straight forward.

How to print a newline in oneliners ...
3 direct replies — Read more / Contribute
by karlgoethebier
on Apr 22, 2014 at 12:23

    Hi all, this one should be self explaining:

    karls-mac-mini:monks karl$ for i in {0..9}; do echo $i; done | perl -p +e '$_++' 12345678910karls-mac-mini:monks karl$

    Ok, but i want a newline:

    karls-mac-mini:monks karl$ for i in {0..9}; do echo $i; done | perl -n +e '$_++; print qq($_\n)' 1 2 3 4 5 6 7 8 9 10

    Quite simple. Got it. But sometimes i struggle a little bit with the essentials :-(

    So i wonder if there is a TMTOWTDI for doing something like this.

    Thank you very much for any hint and best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

Output web page with Padre ... How ?
2 direct replies — Read more / Contribute
by dofski
on Apr 20, 2014 at 11:49

    I am very newbie ... one week

    I use Windows 7

    I installed Apache ... it works with,

    Http:\\localhost test, and is running.

    I installed Dwimperl. I can run simple Perl programs from the command line and Padre.

    I had great pain but eventual success to get local host to output Hello World as web page,

    code is in, it is:

    #!C:\Dwimperl\Perl\bin\perl print "Content-type:text/html\n\n"; print "<html>\n"; print "<h1>Hello World</h1>\n"; print "</html>\n";

    After many trials it worked when I put in,


    Now I open in Padre. when I run, the code is just output in the command line with the script as above. No web page with just Hello World appears.

    I checked view options in Padre and chose HTML ... but on run get error ... no execution mode was defined etc Perhaps I need to install some CPAN modules ?

    Any advice greatly appreciated as I've surfed and read without success.


The 'eval "require $module; 1"' idiom
6 direct replies — Read more / Contribute
by sedusedan
on Apr 19, 2014 at 01:04

    Could someone refresh me on why the ; 1 part is necessary again? In other words, why is this idiom safer/better/more correct than just eval "require $module", especially in the context of using the expression in conditional (e.g.: eval "require $module; 1" or warn "Can't load $module";). I've used this idiom for years, and recently even submitted a patch to Log::Log4perl related to this. But for the love of heaven, I forgot why it's needed in the first place. Let's consider the cases:

    Case 1. Module cannot be not found on the filesystem. require dies with message "Can't locate $module in @INC ...", eval traps it and sets $@ and returns undef. ; 1 part in idiom is not needed (unreached).

    Case 1b. Like case 1, but previous attempt has been made. Ditto.

    Case 2. Module has compile errors. require dies with compile error message, eval traps it and sets $@ and returns undef. ; 1 part in idiom is not needed (unreached).

    Case 2b. Like case 2, but previous attempt has been made. After the first attempt, the entry in %INC is set to undef. At the second attempt, require will die with message "Attempt to reload $module aborted", eval traps it, sets $@, and returns undef. ; 1 part in idiom is not needed (unreached).

    Case 3. Module is loaded successfully and returns a true value (in other words, the normal success case). require will return 1. ; 1 part in idiom is not needed.

    Case 3b. Like Case 3, but previous loading has been made. require will return 1. ; 1 part in idiom is not needed.

    Case 4. Module is loaded successfully but returns a non-true value. require will die with message "$module did not return a true value ...". eval traps it, sets $@, and returns undef. ; 1 part in idiom is not needed (unreached).

    Case 4b. Like case 4, but previous attempt has been made. Ditto.

    There are other cases possible (like a permission error when reading source file, require() being overriden, etc) but the above are the common/majority cases. So what cases does the ; 1 part cover? Does this have something to do with older versions of perl (I'm testing this on 5.18.2).

Using 64 Bit Perl for Production Scripts.
9 direct replies — Read more / Contribute
by pmu
on Apr 18, 2014 at 08:31

    Respected Monks,

    We're going get a new set of SAN Management Servers and I am planning to install Strawberry Perl Version (64 Bit) on it. I googled about it and found that its often recommended to stick to 32 Bit Perl eventhough the OS is 64 Bit because 64 bit versions of some Perl Modules have issues. Is that still the case or can I go ahead using 64 Bit Perl?

    Please let me know.

    -------------------------------------------------------------- Perspectum cognitio aeterna --------------------------------------------------------------
New Meditations
The 10**21 Problem (Part I)
2 direct replies — Read more / Contribute
by eyepopslikeamosquito
on Apr 21, 2014 at 13:01

    When I looked for magic formulae, etc., I would give up after 20 minutes!

    -- Jasper

    Unlike Jasper, I have spent more than 20 minutes searching for magic formulae. Especially ancient Roman ones. I first became aware of them back in 2006 during the Fonality Christmas Golf Challenge where I was astonished by Ton's ingenuity and deviousness in constructing his original HART (Hospelian Arabic to Roman Transform) magic formula.

    Shortly after the Fonality game, hosted an endless competition where you must convert the other way, from Roman to Decimal. By 2009, I had managed to take the lead in all four languages (Perl, Python, Ruby, PHP), as detailed in this series of nodes. And the winning solutions -- in all four languages -- all used (quite different) magic formulae!

    To refresh your memory, the codegolf game rules were essentially:

    Convert a Roman numeral to its integer value. The input numeral, provided on stdin followed by a single newline, is guaranteed to be in the range I to MMMCMXCIX (1 to 3999). For example, given IV on stdin, your program should print 4 to stdout.

    As you might expect, a key component of solutions to this game is mapping individual Roman letters to their decimal equivalents. To help us focus on that, let's define a simpler spec:

    Write a function to convert a single Roman Numeral letter to its decimal equivalent. The function assumes the Roman letter is in $_ and returns its decimal equivalent.

    To clarify, here's a sample (non-golfed) Perl solution:

    sub r { my %h = ( I=>1, V=>5, X=>10, L=>50, C=>100, D=>500, M=>1000 ); return $h{$_}; } print "$_: ", 0+r(), "\n" for (qw(I V X L C D M));
    Running this program produces:
    I: 1 V: 5 X: 10 L: 50 C: 100 D: 500 M: 1000

    Lookup Table vs Magic Formula

    In code golf, there is often a battle between a lookup table and a magic formula. So it proved here. When converting from Roman to Decimal, magic formula trumps lookup table.

    Here are three attempts to solve this problem using a lookup table:

    sub r {%h=(I,1,V,5,X,10,L,50,C,100,D,500,M,1000);$h{$_}} sub r {M1000D500C100L50X10V5I1=~$_;$'} sub r {M999D499C99L49X9V4I=~$_+$'}

    And here are some of my earliest magic formulae from 2007:

    sub r {5**y/VLD//.E.(3*/M/+2*/C|D/+/X|L/)} sub r {1 .E.~-ord()*41%52%5>>y/VLD//} sub r {5**y/VLD//.E.ord()x3%75%50%4} sub r {1 .E.(72^ord)*5/7%5>>y/VLD//} sub r {5**y/VLD//.E.(42^88*ord)%5} sub r {1 .E.(3^77%ord)%7>>y/VLD//}
    Back then, my magic formulae searching skills were so poor that I erroneously concluded that the lookup table approach was better. :-)

    Later, when I tackled this problem in Python, I really needed to use each Roman letter once only in the formula, which forced me to explore alternative approaches ... which, in turn, led to still shorter Perl magic formulae, such as:

    sub r {10**(7&69303333/ord)%9995} sub r {10**(7&5045e8/ord)%2857} # needs 64-bit Perl sub r {IXCMVLD=~$_;"1E@-"%9995}
    Back in the good old days, the little search programs that uncovered these solutions took hours to run, not years. :-)

    The long numbers (such as 69303333 above) that began popping up in these formulae were an indication that the ord function didn't scale very well as the required solutions became less probable. Can we find a built-in function better suited to Roman magic formulae? In PHP and Python, yes. In Perl and Ruby, probably not. At least, I don't know of one.

    The PHP built-in md5 function is perfect for Roman magic formulae. Not only does it generate all required digits (0-9), it generates little else (just a-f). Moreover, you can use all 256 characters in a magic formula, compared to just ten (0-9) for ord. To illustrate, in an eight character magic string (for example 69303333), there are just 10**8 combinations available for ord, while there are a mind-boggling 256**8=1.8*10**19 combinations available for md5! This is a huge advantage when searching for highly improbable solutions, as we shall see later.

    The Python hash function is also superior to ord, though not as good as PHP's md5. This is because Python's Unicode and character escaping claptrap limits you to 125 characters (namely ord 1..9,11,12,14..127) that can be used as input to the hash function without special treatment. Still, 125 is a huge improvement over 10! One drawback of hash compared to md5 is that it generates huge numbers, forcing you to waste five strokes with %1001 to trim the generated numbers into the required Roman Numeral range (1-1000).

    In some cases, the Perl crypt built-in could be employed, though it is not well-suited to this specific problem because (unlike md5) it generates many other characters in addition to the desired 0-9.

    To recap, the shortest magic formulae found so far in all four languages (as detailed in this series of nodes) are:

    10**(205558%ord(r)%7)%9995 # Python hash(r+"magicstrng")%1001 # Python (finding magicstrng is the subjec +t of this node!) 10**(7&5045e8/ord)%2857 # Perl (64-bit) IXCMVLD=~$_;"1E@-"%9995 # Perl 10**(494254%r/9)%4999 # Ruby (no need for explicit ord in this g +ame) md5($r.magicstrng) # PHP (finding magicstrng is an unsolved p +roblem) md5($r.PQcUv)&uppp # PHP wins due to superb mf properties of +md5

    The 10**21 Problem

    There's just no sane regularity in this thing. But in "random" mappings with a very small result set like this, the shortest solution is often to make up some magic formula that has no particular meaning, but just happens to give the wanted result.

    -- Ton Hospel explaining his original decimal-to-roman magic formula

    When Ton Hospel invented magic formulae in golf way back in 2004, he correctly noted that they work best "with a very small result set". Indeed, if there were only five Roman Numeral letters, rather than seven, we would have a straightforward 10**15 problem, rather than a (borderline intractable) 10**21 problem. Why 10**21?

    Suppose you have a magic formula that produces a random number between 1 and 1000. The probability of scoring a (lucky) hit for one numeral is therefore 1 in 1000. Since probabilities multiply, the probability of hitting five out of five numerals is 1 in 10**15, while the chance of hitting all seven Roman Numerals is a daunting 1 in 10**21. Though 1 in 10**21 sounds improbable in the extreme, if you could generate 10**21 combinations, you would not need luck, indeed you would expect to find such an improbable solution. Yet how long would it take to search 10**21 combinations for the elusive (lucky) one?

    Well, if you could perform 10,000 search operations per second, the time required to search 10**21 combinations is a mere 10**21/10000 seconds = 10**17 seconds = 3,170,979,198 years! By the way, this "brute force search infeasibility problem" is why you are asked to create longer and longer passwords, and with a wider range of characters in them, as computer speeds improve. Indeed, Password cracking and magic formula searching are closely related disciplines, the lack of a "codegolf magic formula" wikipedia page notwithstanding. :-)

    To make this theoretical argument more concrete, consider searching for a Roman to Decimal magic formula using the Python built-in hash function. Since this hash function produces very large values, we need to apply %1001 to it so as to produce an essentially random value in the desired 1..1000 range. We might try searching for such a magic formula using a simple Python brute-force search program, such as:

    import time print time.time(), time.clock() for q0 in range(1, 128): for q1 in range(1, 128): for q2 in range(1, 128): for q3 in range(1, 128): for q4 in range(1, 128): for q5 in range(1, 128): for q6 in range(1, 128): for q7 in range(1, 128): for q8 in range(1, 128): for q9 in range(1, 128): magic = chr(q0)+chr(q1)+chr(q2)+chr(q3)+chr(q4)+chr(q5)+chr( +q6)+chr(q7)+chr(q8)+chr(q9) m = hash("M" + magic) % 1001 if m != 1000: continue d = hash("D" + magic) % 1001 if d != 500: continue c = hash("C" + magic) % 1001 if c != 100: continue l = hash("L" + magic) % 1001 if l != 50: continue x = hash("X" + magic) % 1001 if x != 10: continue v = hash("V" + magic) % 1001 if v != 5: continue i = hash("I" + magic) % 1001 if i != 1: continue print "bingo!", q0, q1, q2, q3, q4, q5, q6, q7, q8, q9 print time.time(), time.clock()
    On my machine, this naive brute force search for a ten-character magic string is expected to find a solution in about 52,887,477 years! Note that, with 127 different values for each character in the string, we need a 10-character magic string to give us the required 127**10 = 1.1e21 = 10**21 combinations.

    Rather than give up at this point, I found this "impossible" 50 million year challenge strangely irresistible ... and was eager to learn about any high performance computing techniques required to solve it.

    I get it -- optimization is a fun game ... one can play all day with unrolling loops, peeling away layers of indirection, and so forth to gain cycles, while piddling away time and energy

    -- davido

    Or, as davido puts it, "optimization is a fun game". Well, I enjoy it. So I started by rewriting the above search program in C++, then kept on refining it until I was able to reduce the running time from fifty million years down to only several years and eventually find a solution. This new series of articles describes that endeavour.

    Please note that this series focuses more on High Performance Computing/Supercomputing/Parallel computing in C/C++/Intel assembler than code golf.

PerlBrew (perlbrew list-modules)
No replies — Read more | Post response
by wjw
on Apr 19, 2014 at 12:28
    has a bug(85493) noted in version 0.63 which has yet to be addressed. I spent a good 2.5 hours trying to figure out why 'perlbrew list-modules' didn't return anything. Finally found the the problem in the bug list at RT CPAN. The actual cause of the problem was pointed out Here on github.
    In simple terms: the command 'list-modules' will not work if you are use'ing or have switch'ed to an alias.
    You must use the full name of the Perl dist you are using as is shown in 'perlbrew list' or 'perlbrew available'.

    Perlbrew is fantastic! (minor rant) It is a bit disappointing that this ticket has been around for 11 months without being addressed. It is not an obvious(to me) issue to find or address. My searches(both here and google) rendered very little. The docs here don't make any mention of this either.
    My hope is that someone may save themselves some time finding this here when faced with this issue.
    Was unsure where to post this, but based on FAQ Re: Posting this seems the best place... please correct me if not.
    ...the majority is always wrong, and always the last to know about it...
    Insanity: Doing the same thing over and over again and expecting different results...
New Cool Uses for Perl
Perl Script to extract host list from Symmetrix DMX Array.
No replies — Read more | Post response
by pmu
on Apr 18, 2014 at 15:43


    As an Storage Administrator who works on EMC Symmetrix Storage Array, many times, I have to extract a list of all the hosts connected to the storage array. This needs to be extracted by logging into the storage array and running a command like symmask -sid 12345 list logins, and then the hostnames are to be extracted from the list and stored in a text file. If hostnames are not reflecting, then the corresponding World Wide Name (WWN) of the Host HBA should be included in the list. To ensure dual or quadruple redunduncy, each host will show two paths or four paths, so the duplicates need to be removed and the host names need to be in Upper case. There are many such arrays, and a seperate file needs to be created for each of them.

    Sometimes, the file has to be regenerated every few minutes due to some changes/requirements and the old file must be deleted, else wrong records will be captured. The script picks the array name from the command output stated earlier. This script is working fine on Redhat Linux 6.4 running Perl Version 5.10.1 and on Windows 2003 running Strawberry Perl version

    Hoping fellow EMC Administrators will find this script useful. Please note - I dont get to write scripts on a regular basis, so there's quite a lot of improvement that can be done with the script. If so, kindly let me know. Here's the script:

    Here's the test file that's fed to the script. The actual file will have much more entries than what's given below.

    And here is the output:

    C:\Users\pmu\Documents\perl\work>perl test_list_logins.tx +t Deleting existing "hostlist_hostnames.pl_000190101234.txt". A new one +will be created. ********************************************************************** +******************* Please Check the file - [ C:\Users\pmu\Documents\perl\work\hostlist_ho +stnames.pl_000190101234.txt ]. NULLs are replaced with corresponding pWWNs. ********************************************************************** +******************* C:\Users\pmu\Documents\perl\work

    And here's what the file - hostlist_hostnames.pl_000190101234.txt contains:

    -------------------------------------------------------------- Perspectum cognitio aeterna --------------------------------------------------------------
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 examining the Monastery: (8)
As of 2014-04-25 01:13 GMT
Find Nodes?
    Voting Booth?

    April first is:

    Results (579 votes), past polls