Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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
in file insert character in every row on nth position
3 direct replies — Read more / Contribute
by ukhare
on Feb 11, 2016 at 13:43


    in a csv file how can i insert a character/special character on particular nth position in every row

    for example file1.csv

    Here is the sample data

    2016-02-06-0240:00 2016-02-06-0540:00 2016-02-06-0740:00

    expected output

    2016-02-06-02:40:00 2016-02-06-05:40:00 2016-02-06-07:40:00
How to wait for putty to finish before proceeding.
3 direct replies — Read more / Contribute
by SwaJime
on Feb 11, 2016 at 12:18

    Howdy again,

    More info: This is Windows 7 Enterprise running ActivePerl 5.16.3

    I've run into another problem.

    Whereas before switching to use pageant, this command does not return control to the calling script until the putty window is closed.

    putty -ssh -l $user $address -t -m $filename

    This command returns immediately and I have no way of knowing when the putty window is closed by the user.

    pageant @ppk_files -c putty -ssh -l $user $address -t -m $filename

    The reason this is a problem is because I'm trying to run two consecutive calls to putty. One to one server setting up data, the second to a second server to process that data, which is not ready until the user closes the first putty session.

    Here are sample files to illustrate: In, the second putty window is not opened until the first putty window is closed. This is the desired behavior. In, the second putty window is opened before the first window is closed. This is not good because the data has not been set up yet.

    #!/usr/bin/perl # use strict; use warnings; system('putty -ssh -l root -t -m C:\Users\JWSIMP~1\AppDa +ta\Local\Temp\BoKFVjf1B9'); system('putty -ssh -l operations -t -m C:\Users\JWSIMP~ +1\AppData\Local\Temp\d60NPopq6A');

    #!/usr/bin/perl # use strict; use warnings; system('pageant F:\.keys\acuroot_1_8_12_rsa.ppk F:\.keys\acuroot_1_8_1 +3_rsa.ppk -c putty -ssh -l root -t -m C:\Users\JWSIMP~1 +\AppData\Local\Temp\BoKFVjf1B9'); system('pageant F:\.keys\operations_rsa.ppk -c putty -ssh -l operation +s -t -m C:\Users\JWSIMP~1\AppData\Local\Temp\d60NPopq6 +A');

    So, long story short ... how can I get that functionality back? I don't want both sessions opening at the same time.

    Please forgive me if this is something that is already documented. I have been searching for an answer for quite some time now.



Multi level dependency structure
4 direct replies — Read more / Contribute
by MH1
on Feb 11, 2016 at 12:09

    Greetings monks, long time lurker, first post. Typically I can googlefoo my way around to find a solution but I'm not sure how to go about that for this problem. I have a flat file consisting of item and item dependencies. But I need to be able to track it back to find all the potential dependencies, basically following the rabbit down the hole.

    Plain Example: if item1 requires item2 and item3, and item3 requires item4 -> then item1 also requires item4.

    I'm working with around 120k rows so I know the relationships are going to be rather complex, however a task is a task.

    Relevant Code:

    #load hash after some parsing in a foreach loop push(@{$jobs{$JobName}{1}}, $blah); ... $level =1; $nextlevel = 2; while ($level <= 10) { foreach my $dep (keys %jobs) { foreach (@{$jobs{$dep}{$level}}) { print "$dep $level $_\n"; push( @{$jobs{$dep}{$nextlevel}},@{$jobs{$_}{$level}} ); next if ${$jobs{$_}{$level}}[0] eq "$dep"; last if ${$jobs{$_}{$level}}[0] eq ''; #this cancels the loop +if any of the dependencies don't have dependencies, which is a proble +m if there's additional } } $level++; $nextlevel++; }

    So one of the problems is the last statement is prematurely breaking the loop if X dep doesn't have a dep, but there's additional deps in the array. Without that terminate feature the script will run until the while loop has been fulfilled, I have no way of breaking out once I have tracked all the dependencies down. As for CPAN and modules, given my environment I'm very limited on what I can use.

    Example Data(first column is job, rest are dependencies):

    job1, job2,job1, job3,job2 job4,job2 job5,job2,job4 job6,jobz joba,job4,jobb jobz,jobbc,job2

    Any guidance will be greatly appreciated!

    I figured it out, made some loop structure changes, thanks VinsWorldcom for your replay

    while ($level <= 10) { foreach $dep (keys %jobs) { foreach (@{$jobs{$dep}{$level}}) { print "Key:$dep Value:$_ Lvl:$level Seen:$seen{$_}\n"; if ($seen{$_} eq '') { push( @{$jobs{$dep}{$nextlevel}},@{$job +s{$_}{$level}} ); } $seen{$_} = 1; next if ${$jobs{$_}{$level}}[0] eq "$dep"; last if $seen{$_} == 1; } } %seen = ''; @temparray = ''; $level++; $nextlevel++; }
Sending a text file using POST
2 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 11, 2016 at 09:51
    Hi Monks!

    I am trying to send text files ( using only one file here ) to a site's directory "", using POST.
    I am getting a 404 error, but the url is correct. I think my problem is with the Perl, am I using the right way to use POST to send a file through HTTPS, any suggestion?
    #!/usr/bin/perl use strict; use warnings; use LWP::UserAgent; use Data::Dumper; my $ua = LWP::UserAgent->new(); my $server_endpoint = ""; # set custom HTTP request header fields my $req = HTTP::Request->new(POST => $server_endpoint); $req->headers(); print Dumper( $req->headers() ); $req->header('x-auth-token' => 'Token e45ttkfksj48sdfj4jd9abcdd'); # add POST data to HTTP request body my $filename = "/var/www/location/first_text.txt"; $req->content($filename); my $resp = $ua->request($req); if ($resp->is_success) { my $message = $resp->decoded_content; print "Received reply: $message\n"; }else { print "HTTP POST error code: ", $resp->code, "\n"; print "HTTP POST error message: ", $resp->message, "\n"; }

    Thanks for looking!
image encode base64 - help needed
1 direct reply — Read more / Contribute
by zurich
on Feb 11, 2016 at 09:27
    Hi everyone

    I'm trying to create a perl script which encodes images to base64. This shall be used to transfer images via xml to another system.

    I created the following script to read the capture.png file:

    use MIME::Base64; open (my $image, 'Z:\capture.png') or die "$!"; $raw_string = do{ local $/ = undef; <$image>; }; $encoded = encode_base64( $raw_string );

    For the beginning, I just re-write into a new file photo.png

    my $decoded= MIME::Base64::decode_base64($encoded); open my $fho, '>', 'Z:\photo.png' or die $!; binmode $fho; print $fho $decoded;

    The photo.png is created with exactly the same size as the input photo, however the newly created file can't be opened.

    I also comared the base64 value with the value created by an online encoding webpage (using the same input photo) and this is different.

    I would be very happy if somebody could help me out with this!

    Thanks a lot in advance. Best regards zurich

How to pick an appender selectively in Log::Log4perl
2 direct replies — Read more / Contribute
by hellosarathy
on Feb 11, 2016 at 08:31
    Dear Monks,

    I have a Log::Log4perl logger configured which writes to STDOUT, SYSLOG and Logfile, like:

    my %loggerConfig = ( "log4perl.category.default_logger" => "INFO, Stdout, SYSLOG, Logfile",
    which writes to STDOUT, SYSLOG and Logfile. Few messages I need to write ONLY to the log file and NOT to syslog and STDOUT. How can this be done?


Copying Charts from Microsoft Excel to microsoft word
3 direct replies — Read more / Contribute
by rohit1994
on Feb 11, 2016 at 08:10
    hey, I'm new to perl, and i have been trying to learn the wide applications of it. the one thing that i have been trying from past few days is to copy specific charts or graphs from an excel file to a word file. I have browsed through a lot of contents on the web, but nothing seems to work. Can you please help me out there??
trying to implement file tail with regular expression
1 direct reply — Read more / Contribute
by mkhayat
on Feb 11, 2016 at 06:06

    I build a script to read from diagnostic file and track a message. in case the message found a service in a server will restarted. I was successful in this however once the script reach end of the file it start again and this mean that it will keep restarting the service. I searched and found that there is library which called file::tail library which is made for this kind of issues unfortunately i was not able to modify my script in able to use this library. I am new in perl and I am trying to find my way into perl world. please help me :)

    use File::Tail; my $diagfile; my $Checkoutput; my $hostName1; my $hostName2; sub init { my ($dir) = @_; my $line; my $var; my $val; open (LREP2, "$dir/config/param.ini"); while ($line = <LREP2>) { chop $line; ($var,$val) = split(/=/, $line); if ($var eq "DIAGFILE") { $diagfile = $val; } if ($var eq "CHECKFILE") { $Checkoutput = $val; } if ($var eq "HOSTNAME1") { $hostName1 = $val; } if ($var eq "HOSTNAME2") { $hostName2 = $val; } } close LREP2; } #MAIN die "Usage: $0 <app_root_dir>" unless @ARGV == 1; my $app_root_dir = shift; &init($app_root_dir); my $line; open (DIAG, "$diagfile"); my $clock = 0; while (1) { open LOGFILE, ">>$app_root_dir/logs/detailedlog.log"; while ($line = <DIAG>) { if ($line =~ /is higher than 5 seconds/) { if ($clock == 0) { $clock = 60; my $commandStr2 = "sc \\\\$hostName1 stop AudioSrv >$a +pp_root_dir\\logs\\StopServiceOutput1.txt" ; print LOGFILE "about to execute=$commandStr2\n"; system($commandStr2); print LOGFILE "just executed=$commandStr2\n"; my $commandStr4 = "sc \\\\$hostName2 stop AudioSrv >$a +pp_root_dir\\logs\\StopServiceOutput2.txt" ; print LOGFILE "about to execute=$commandStr4\n"; system($commandStr4); print LOGFILE "just executed=$commandStr4\n"; sleep(5); my $commandStr3 = "sc \\\\$hostName1 start AudioSrv >$ +app_root_dir\\logs\\StartServiceOutput1.txt"; print LOGFILE "about to execute=$commandStr3\n"; system($commandStr3); print LOGFILE "just executed=$commandStr3\n"; my $commandStr5 = "sc \\\\$hostName2 start AudioSrv >$ +app_root_dir\\logs\\StartServiceOutput2.txt"; print LOGFILE "about to execute=$commandStr5\n"; system($commandStr5); print LOGFILE "just executed=$commandStr5\n"; } $clock --; sleep(1); } close LOGFILE; } sleep(65); }
Multiple values assigned to same key in hashes
2 direct replies — Read more / Contribute
by achs
on Feb 11, 2016 at 03:48
    Hi, Below I pasted a code that I got from here for assigning multiple values to the key in perl hashes. This code is working for one and not for the other. I don't understand where it is going wrong. If anybody can help me do this, it will be hugely appreciated. use strict; use warnings; use diagnostics; use Data::Dumper; my %hash; my $key; my $value; my @data = ("foo",1, "bar",2, "foo",3, "baz",4); while ($key = shift (@data)) { $value = shift (@data); # push the value on the array push @{$hash{$key}}, $value; } print Dumper \%hash; The array in the two cases mentioned is different. I am getting output as below where you can see the keys not as usual. I am not able to access the keys also, basically it is not getting.
Perl Sort date and time inside csv file
4 direct replies — Read more / Contribute
by ukhare
on Feb 11, 2016 at 02:06


    My file file.csv is having some columns among which column 1 represents date and time, I am trying to sort it by date and time but it is sorting only based on time. please check and suggest.

    #!/usr/bin/perl use strict; my $input_dir = "d://perl//output"; my $output_dir = "d://perl//output"; my $input_file = "$input_dir//file.csv"; my $output_file = "$output_dir//output2_file.csv"; open (OUTPUT, ">>$output_file") or die "Error 016: Error creating $out +put_file \n"; open (INPUT, "<$input_file") or die "Error 001: Error locating file $i +nput_file \n"; my @array =(<INPUT>); #print "Array\n"; #@print join( "\n", @array )."\n\n"; print "Sort Date\n"; print join( "\n", @sortedTime )."\n\n"; print OUTPUT; close (OUTPUT); close (INPUT);

    data in file.csv looks like





Add your question
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!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            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?

    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 having an uproarious good time at the Monastery: (11)
    As of 2016-02-12 00:02 GMT
    Find Nodes?
      Voting Booth?

      How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

      Results (384 votes), past polls