Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
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
Way to calculate day-of-the-week
4 direct replies — Read more / Contribute
by sylph001
on Dec 24, 2014 at 03:42

    Hi everyone,

    Recently I'm writing a small perl program and I find out that for some certain day-of-the-month numbers, I need to count out the corresponding day-of-the-week numbers.

    I could write a routine to do that work but turns out it will be complicated.

    I think there must be some precedences done for doing this work.

    I guess there might be some useful functions in modules like Local::Time or so, but I feel not familiar with the wider industry and standard way that most people do it with.

    So, could you kindly lead me to the best/most-common way to do this date calculation?

     

    Many thanks

    </body> </html>
calling subroutine inside loop - ERROR - subroutine executes only once
3 direct replies — Read more / Contribute
by kaushik9918
on Dec 24, 2014 at 02:42

    I am trying to call a subroutine in a loop, but its exiting after executing the sub only once. Any idea why? Or can someone point me to a similar question posted before in this forum?

    the array corners contains: @corners= AAA BBB CCC DDD

    and my code is :
    while(<CORNERS_LIST>){ $_=~ s/\s+/ / ; chop $_; push @corners, $_ ; print "\n@corners\n"; } my $corner; foreach(@corners){ $corner=$_; &loading_tsc; } sub loading_tsc{ chdir($corner) or die "\n $!\n"; print "\n"; print `pwd`; print "\n"; }

    But the result I am getting is :

    /file/path/is/AAA No such file or directory

    The desired result I wanted to see is

    /file/path/is/AAA /file/path/is/BBB /file/path/is/CCC /file/path/is/DDD
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&#9792;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&#9792;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?

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 exploiting the Monastery: (5)
    As of 2014-12-27 07:45 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

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





      Results (176 votes), past polls