Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Seekers of Perl Wisdom

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

If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
Unable to open file.
3 direct replies — Read more / Contribute
by shain
on Dec 24, 2014 at 01:48
    I cannot figure out why this is failing so consistently. I feel like there is some small thing I am doing that is causing it to fail to parse the path.
    use warnings; use strict; use IO::File; use feature('say'); sub openFile{ my $file = shift; #open my $fh, '>' , $file or die $!; my $fh = IO::File->new(); if ($fh->open(">> $file")){ say "I opened $file"; $fh->close; } else { say "failed to open $file $! "; } } openFile('C:\Users\Shain\AppData\Roaming\WaterAccount\file.log'); openFile("C:\Users\Shain\AppData\Roaming\WaterAccount\file.log"); openFile('$ENV{APPDATA}\WaterAccount\file.log'); openFile("$ENV{APPDATA}\WaterAccount\file.log"); openFile('C:\\Users\\Shain\\AppData\\Roaming\\WaterAccount\\file.log') +; openFile("C:\\Users\\Shain\\AppData\\Roaming\\WaterAccount\\file.log") +; openFile('$ENV{APPDATA}\\WaterAccount\\file.log'); openFile("$ENV{APPDATA}\\WaterAccount\\file.log"); openFile('C:\/Users\/Shain\/AppData\/Roaming\/WaterAccount\/file.log') +; openFile("C:\/Users\/Shain\/AppData\/Roaming\/WaterAccount\/file.log") +; openFile('C:/Users/Shain/AppData/Roaming/WaterAccount/file.log'); openFile("C:/Users/Shain/AppData/Roaming/WaterAccount/file.log"); openFile('$ENV{APPDATA}/WaterAccount/file.log'); openFile("$ENV{APPDATA}/WaterAccount/file.log");

    Output:

    C:\Users\OWNER\Documents\Work\Perl>perl file.pl Unrecognized escape \S passed through at file.pl line 22. Unrecognized escape \A passed through at file.pl line 22. Unrecognized escape \R passed through at file.pl line 22. Unrecognized escape \W passed through at file.pl line 22. Unrecognized escape \W passed through at file.pl line 25. failed to open C:\Users\Shain\AppData\Roaming\WaterAccount\file.log No + such file or directory failed to open C:SERSSHAINAPPDATAROAMINGWATERACCOUNT♀ILE.LOG Inv +alid argument failed to open $ENV{APPDATA}\WaterAccount\file.log No such file or dir +ectory failed to open C:\Users\OWNER\AppData\RoamingWaterAccount♀ile.lo +g Invalid argume nt failed to open C:\Users\Shain\AppData\Roaming\WaterAccount\file.log No + such file or directory failed to open C:\Users\Shain\AppData\Roaming\WaterAccount\file.log No + such file or directory failed to open $ENV{APPDATA}\WaterAccount\file.log No such file or dir +ectory failed to open C:\Users\OWNER\AppData\Roaming\WaterAccount\file.log No + such file or directory failed to open C:\/Users\/Shain\/AppData\/Roaming\/WaterAccount\/file. +log No suc h file or directory failed to open C:/Users/Shain/AppData/Roaming/WaterAccount/file.log No + such file or directory failed to open C:/Users/Shain/AppData/Roaming/WaterAccount/file.log No + such file or directory failed to open C:/Users/Shain/AppData/Roaming/WaterAccount/file.log No + such file or directory failed to open $ENV{APPDATA}/WaterAccount/file.log No such file or dir +ectory failed to open C:\Users\OWNER\AppData\Roaming/WaterAccount/file.log No + such file or directory
How to populate a HASH using a FOR loop to a FUNCTION
3 direct replies — Read more / Contribute
by Gigiux
on Dec 23, 2014 at 19:18

    Dear all,
    I am trying to learn Perl and I am stuck with the hash section. I would like to implement a function (subroutine) that I could call when required to populate the hash with new elements.
    The way I have done it is to create a FOR loop in which at each cycle a function is called; the function gets the key and value and the link to the hash. The function then returns the hash.
    In theory the function gets the variables directly from the keyboard but for this example I have set a variable with some strings.
    The function I have implemented actually properly gets the variables and store them in the hash, however at each cycle the hash is reset so the hash is not populated but just hosts the last couple of values that is fed with.

    Is there a way to store the values permanently, so that the hash can be populated a bit at the time?

    Thank you for any help.
    Gigiux

    here is the code i have written

    use strict; my(@myArray); my(%myHash); my($myLoop, $key, $val, $myTemp, $i); @myArray = qw( sean connery george lazemby roger moore timothy dalton +pierce brosnan ); $myLoop = 5; print("The array is: @myArray\n"); for($i = 0; $i < $myLoop; $i++){ print("\nElement number $i\n"); $key = shift(@myArray); $val = shift(@myArray); print("The key is: $key\nThe value is: $val\n"); %myHash = &makeHash($key, $val, \%myHash); print("The hash at cycle $i is: "); print %myHash; $myTemp = $myHash{$key}; print("\nThe actual value for \"$key\" is: $myTemp\n"); } print("\nThe hash is not functional, in fact the value for \"sean\" is +: "); $key = "sean"; $myTemp = $myHash{$key}; print $myTemp; print("\n(that was an empty result)\n"); sub makeHash { my($key); my($val); my(%subHash); $key = shift @_; $val = shift @_; %subHash = shift @_; print("In the function, the key is $key and the value is $val\n"); print("The hash at the beginning is: "); print %subHash; $subHash{$key} = $val; print("\nThe hash at the end is: "); print %subHash; print("\n"); return(%subHash); }

    the result from the first two cycles and at the end of the loop is as follows:

    The array is: sean connery george lazemby roger moore timothy dalton p +ierce brosnan Element number 0 The key is: sean The value is: connery In the function, the key is sean and the value is connery The hash at the beginning is: HASH(0x1bfd938) The hash at the end is: HASH(0x1bfd938)seanconnery The hash at cycle 0 is: HASH(0x1bfd938)seanconnery The actual value for "sean" is: connery Element number 1 The key is: george The value is: lazemby In the function, the key is george and the value is lazemby The hash at the beginning is: HASH(0x1bfd938) The hash at the end is: georgelazembyHASH(0x1bfd938) The hash at cycle 1 is: HASH(0x1bfd938)georgelazemby The actual value for "george" is: lazemby ... The hash is not functional, in fact the value for "sean" is: (that was an empty result)

    Note: even if I remove the link to the hash, the results are slightly different ("sean" is kind of stuck to the array but it is lost at the end of the implementation) but the hash does not get properly populated.

Onliner magic to remove files
4 direct replies — Read more / Contribute
by glasswalk3r
on Dec 23, 2014 at 14:40

    Greetings monks,

    I'm trying to figure out how this onliner to remove files works:

    for(<*>){((stat)[9]<(unlink))}

    The "*" in the diamond operator is something I can't find any document about it.

    Also, calling stat (which will hit $_, filled by the diamond operator of any filename in the current directory) and getting a slice of it (returning mtime of the file as the ninth element of the list) makes no sense to me, specially how the filename information is being given to unlink.

    Besides that, calling stat for me makes no sense at all... I could be calling unlink directly, couldn't I? At least it works if I replace everything with an print "$_\n" inside the for loop.

    Here is the reference from where I fetched this onliner: http://www.slashroot.in/which-is-the-fastest-method-to-delete-files-in-linux.

    Thanks,

    Alceu Rodrigues de Freitas Junior
    ---------------------------------
    "You have enemies? Good. That means you've stood up for something, sometime in your life." - Sir Winston Churchill
Math::round not rounding correctly
9 direct replies — Read more / Contribute
by bulrush
on Dec 23, 2014 at 14:26
    Perl 5.8.8 on Redhat Linux

    I'm doing "use Math::Round qw(:all)" and later in my program doing "$l=round($x)" where $x is 3461.5. $l ends up being 3461 when it should be 3462. How can I ensure Math::Round is being used?

    I have not used Math::Round before. And there is no "round" in my utils include file or anywhere else, otherwise I'd get an error at some time.

    Thanks.

    p.s. I have tried using several rounding methods after doing some Googling and it looks like Math::Round would work best. I seem to have the most problems with numbers ending with .5.

    EDIT: This gave me no error, but it also did not round correctly to 3462.

    $x=$l1*$l2;
    $l=Math::Round::round($x);
    
    In my main program: The sprintf method doesn't round correctly in all cases, and neither does using POSIX ceil() and floor() in my main program. My test program works, but not my main perl program. So I was trying to ensure the Math::Round::round() function was being called.

    EDIT 2: When the number is 3461.5 it should round to 3462 but rounds to 3461. How do I round this correctly? Try these test programs at the shell prompt. The first program rounds to 2 decimals. The second to 0 decimals to show the rounding problem. This is the actual calculation I'm having trouble with.

    perl -e 'print sprintf("%.4f",(3010*1.15))."\n"' # Outputs 3461.5000
    perl -e 'print sprintf("%.2f",(3010*1.15))."\n"' # Outputs 3461.50
    perl -e 'print sprintf("%.0f",(3010*1.15))."\n"' # Outputs 3461
    
Archive::Zip install fails on Strawberry Perl
2 direct replies — Read more / Contribute
by zartperl
on Dec 23, 2014 at 11:50

    I installed Strawberry Perl. I then tried to install Archive::Perl module using CPAN, failed. I then tried installing other modules like Log::Log4perl, successful. Has anyone else encountered problems with this module on a Win-x64 platform?

    Summary of my perl5 (revision 5 version 20 subversion 1) configuration:

    Platform: osname=MSWin32, osvers=6.3, archname=MSWin32-x64-multi-thread uname='Win32 strawberry-perl 5.20.1.1 #1 Mon Sep 15 13:26:45 2014 +x64' config_args='undef' hint=recommended, useposix=true, d_sigaction=undef useithreads=define, usemultiplicity=define use64bitint=define, use64bitall=undef, uselongdouble=undef usemymalloc=n, bincompat5005=undef Compiler: cc='gcc', ccflags =' -s -O2 -DWIN32 -DWIN64 -DCONSERVATIVE -DPERL +_TEXTMODE_SCRIPTS-DPERL_IMPLICIT_CONTEXT -DPERL_IMPLICIT_SYS -DUSE_PE +RLIO -fwrapv -fno-strict-aliasing -mms-bitfields', optimize='-s -O2', cppflags='-DWIN32' ccversion='', gccversion='4.8.3', gccosandvers=''

    Error Summary:

    Test Summary Report ------------------- t/02_main.t (Wstat: 512 Tests: 47 Failed: 7) Failed tests: 25, 32-34, 38, 46-47 Non-zero exit status: 2 Parse errors: Bad plan. You planned 141 tests but ran 47. t/03_ex.t (Wstat: 1536 Tests: 17 Failed: 6) Failed tests: 4, 6, 10, 13-14, 16 Non-zero exit status: 6 Files=16, Tests=140, 9 wallclock secs ( 0.09 usr + 0.13 sys = 0.22 +CPU) Result: FAIL Failed 2/16 test programs. 13/140 subtests failed. dmake.exe: Error code 255, while making 'test_dynamic' PHRED/Archive-Zip-1.39.tar.gz C:\STRAWB~1\c\bin\dmake.exe test -- NOT OK //hint// to see the cpan-testers results for installing this module, t +ry: reports PHRED/Archive-Zip-1.39.tar.gz Stopping: 'install' failed for 'Archive::Zip'. Failed during this command: PHRED/Archive-Zip-1.39.tar.gz : make_test NO

    Complete install output -

    cpan> install Archive::Zip Running install for module 'Archive::Zip' Checksum for C:\STRAWB~1\cpan\sources\authors\id\P\PH\PHRED\Archive-Zi +p-1.39.tar.gz ok Configuring P/PH/PHRED/Archive-Zip-1.39.tar.gz with Makefile.PL Checking if your kit is complete... Looks good Generating a dmake-style Makefile Writing Makefile for Archive::Zip Writing MYMETA.yml and MYMETA.json PHRED/Archive-Zip-1.39.tar.gz C:\strawberry\perl\bin\perl.exe Makefile.PL make=dmake -- OK Running make for P/PH/PHRED/Archive-Zip-1.39.tar.gz cp lib/Archive/Zip/ZipFileMember.pm blib\lib\Archive\Zip\ZipFileMember +.pm cp lib/Archive/Zip/MockFileHandle.pm blib\lib\Archive\Zip\MockFileHand +le.pm cp lib/Archive/Zip/DirectoryMember.pm blib\lib\Archive\Zip\DirectoryMe +mber.pm cp lib/Archive/Zip/FileMember.pm blib\lib\Archive\Zip\FileMember.pm cp lib/Archive/Zip/NewFileMember.pm blib\lib\Archive\Zip\NewFileMember +.pm cp lib/Archive/Zip/MemberRead.pm blib\lib\Archive\Zip\MemberRead.pm cp lib/Archive/Zip/Member.pm blib\lib\Archive\Zip\Member.pm cp lib/Archive/Zip/Tree.pm blib\lib\Archive\Zip\Tree.pm cp lib/Archive/Zip/Archive.pm blib\lib\Archive\Zip\Archive.pm cp lib/Archive/Zip/FAQ.pod blib\lib\Archive\Zip\FAQ.pod cp lib/Archive/Zip/BufferedFileHandle.pm blib\lib\Archive\Zip\Buffered +FileHandle.pm cp lib/Archive/Zip.pm blib\lib\Archive\Zip.pm cp lib/Archive/Zip/StringMember.pm blib\lib\Archive\Zip\StringMember.p +m "C:\strawberry\perl\bin\perl.exe" -MExtUtils::Command -e cp -- script/ +crc32 blib\script\crc32 pl2bat.bat blib\script\crc32 PHRED/Archive-Zip-1.39.tar.gz C:\STRAWB~1\c\bin\dmake.exe -- OK Running make test "C:\strawberry\perl\bin\perl.exe" "-MExtUtils::Command::MM" "-MTest::H +arness" "-e" "undef *Test::Harness::Switches; test_harness(0, 'blib\l +i b', 'blib\arch')" t/*.t t/01_compile.t ................ ok

Perl oracle insert error handling
4 direct replies — Read more / Contribute
by homer4all
on Dec 23, 2014 at 11:09
    Hello Monks,

    I'm trying to put logic into perl coding but not able to do so for sometime now.

    What I'm trying to do is

    1. Open csv file

    2. Insert line into Oracle table

    3. If any error then

    3.1 Rollback all inserts of the file

    3.2 Update status table with FAILURE

    3.3 Move to next file

    4. If all inserts completed then

    4.1 Update status table with SUCCESS

    5. Commit

    Could some expert monks help me out sorting this logic?
    use warnings; use strict; use Text::CSV; use DBD::Oracle; my $exitStatus = 0; # Connect to database and disable autocommit my $dbAgent = OracleAgent->dbLogin(dbName); $dbAgent->connect(); $dbAgent-> setAutoCommit(0); #@csvFile holds all csv files list to load in db foreach my $file (@csvFile) { chomp ($item); &insertRecords($file); } $logFile-> ("Exit status"); #---------------- sub insertRecords { my $csv; my $fileToInsert = shift; my $row; my $SQL; my $sth; my $dbh; my $rc; open my $fh, "<", $fileToInsert or die "$filetoInsert: $!" $logFile -> ("Working under $file") while ($row = $csv->getline ($fh)) { $SQL1 = "Insert into TAB1 (sample_date, server, first, n1, n2) values (?,?,?,?,?)"; $sth = prepare($SQL1) $sth -> execute($row[0], $row[1], $row[2], $row[3], $row[4]) || { logFile($DBI::errstr); $dbAgent->rollback; $rc=0; #if error in insert then update status table $SQL3 = "Insert into STATUS (sample_date, server +, cvs_file, row_count, status) values (sysdate,$row[1],$file,$rc,'FAI +LURE')"; $sth = executeQuery($SQL3); } else { #if no error in insert then update status table an +d commit everything $SQL2 = "Insert into STATUS (sample_date, server, + cvs_file, row_count, status) values (sysdate,$row[1],$file,$rc,'SUCCESS')"; $sth = executeQuery($SQL2); $rc++; } close $fh; $dbAgent->commit;
what are blib lib _build ??
1 direct reply — Read more / Contribute
by Anonymous Monk
on Dec 23, 2014 at 09:55

    When I do this:

    module-starter --mb --module="Animal" --email="a@example.com" perl Build.PL ./Build

    directories such as blib lib t _build are created

    What does these directories exactly do? I know t is test directory but I have no idea about blib,lib,_build directory

How to hide the Contents in script
5 direct replies — Read more / Contribute
by DVCHAL
on Dec 23, 2014 at 03:37
    Hi monks, I wanted to know, is there any way to hide the Content in Script before giving it to Third party users. I dont want others to see the script, it will be better to provide only the executable(exe) like files. Is there any way to do that?
[Re]confirm box
1 direct reply — Read more / Contribute
by kbee
on Dec 23, 2014 at 03:02

    I am in an unique 'perl' situation in trying to embed a reconfirm box into an existing perl/cgi script, and let the perl script continue processing through its code based on the yes/no response of the user. To further describe my situation, the user currently launches an operational webpage and selects an app service and an actioneither activate, de-activate or check status and clicks submit. A confirm box shows up to accept the yes/no response from the user. A yes response results in the servicename and action passed onto the perl/cgi script which goes ahead in carrying out the selected action while displaying the results in a separate window with appropriate header and footer information. I needed to embed a confirm box again into the perl code if the action was 'de-activate' and have perl hold its further processing until the user responds back with a yes again. So far after googling through web postings and using perl/javascript snippet examples, the perl/cgi script does throw up the second confirm box if the action is de-activate, but it continues onward irrespective of a response from the box or not. I have attached sections of the code below and appreciate your expert advice from you perl monks. Though I am familiar with perl programming, integrating the second confirm box has been a challenge. Thanks for reading my post.

    #!/usr/bin/perl -w # use CGI; use CGI::Carp qw (fatalsToBrowser); use Cwd; use lib getcwd . '/lib'; use COI::INIFile; use COI::Logger; use File::Basename; use COI::Commands; use Sys::Hostname; use strict; ...... ...... my $q = CGI->new; print $q->header('text/html'); #print $q->Dump(%ENV); ### get values from html form my $username = $q->param("username"); my $action = $q->param("option_1") ; my $service = $q->param("option_2") ; print "</left><pre>\n"; &print_header; if ( $action eq 'Status') { my $wait_for_user_response = "yes"; if(defined($q->param("userresponse"))) { if($q->param("userresponse") eq "yes") { print "go ahead \n"; } else { print "don't go ahead \n"; } } print "<html>\n"; print "<head>\n"; print "<LANGUAGE=Javascript>\n"; print "<script>\n"; print "function CheckForm_onclick()\n"; print "{\n"; print "var myForm = document.form1;\n"; print "var message = \"\";\n"; print "message = \"Confirm if you need to disable $ser +vice. Choose OK to go ahead and Cancel to abort.\";\n"; print "var answer = confirm(message);\n"; print "if (answer == false ){ \n"; print "document.write(\'You chose to Cancel. Closed wi +ndow.\');\n"; print "}\n"; print "else {\n"; print "document.getElementById(\"userresponse\").value + = \"Yes\";\n"; print "document.form.submit();\n"; print "}\n"; print "}\n"; print "</SCRIPT>\n"; &reconfirm_form; } print "\n Going ahead made it\n"; &footer(); sub reconfirm_form { print "<title>$tool_desc</title>\n"; print "</head>\n"; print "<body onload=\"return (CheckForm_onclick())\">\n"; print "<FORM action=\"disable.cgi\" method=\"post\">\n"; print "<input type=\"hidden\" name=\"userresponse\" >\n"; print "</form>\n"; print "</body>\n"; print "</html>\n"; }
Have a multiple file in directory and want to manipulate in each files in incremental order. All the file have same value.
3 direct replies — Read more / Contribute
by hemantjsr
on Dec 23, 2014 at 02:34

    Please find below Working Code. It's giving error message "Use of uninitialized value $lines1 in substitution (s///) a"

    apart from that it's giving a result like in a file01.txt have now file01.txt, in file02.txt have file02.txt only and so on. Old values are deleted and only filename are comeing file.

    where as i needed output like

    file01.txt have 11 10,9:10/4947000219 :20140924105028 24

    file02.txt have 11 10,9:10/4947000220 :20140924105228 24

    file03.txt have 11 10,9:10/4947000221 :20140924105428 24

    file04.txt have 11 10,9:10/4947000222 :20140924105628 24

    #!/usr/bin/perl use strict; use 5.10.0; # For autodie and regex \K use autodie; use File::Find; use Time::Piece; use Time::Seconds qw/ ONE_MINUTE /; use constant DATE_FORMAT => '%Y%m%d%H%M%S'; my $n; my $directory="/home/e/Doc/AutoMation"; chdir $directory; opendir(DIR, ".") or die "couldn't open $directory: $!\n"; foreach my $file (readdir DIR) { next unless -f $file; open my $in_fh, '<',$file; my @lines = <$in_fh>; close $in_fh; ++$n; $lines[0] =~ s~/4947000219/\K(4947000210+)~$1+$n~e; $lines[1] =~ s{:20140924105028\K(20140924105028+)}{ my $tp = Time::Piece->strptime($1, DATE_FORMAT); ($tp + ONE_MINUTE * 2 * $n)->strftime(DATE_FORMAT); }e; open my $out_fh, '>', $file; print $out_fh @lines; close $out_fh; } closedir DIR;

Add your question
Title:
Your question:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":


  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • 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 avoiding work at the Monastery: (12)
    As of 2014-12-26 15:49 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      Is guessing a good strategy for surviving in the IT business?





      Results (171 votes), past polls