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 Understand grep and hash use for prime no.
5 direct replies — Read more / Contribute
by shankonit
on Aug 03, 2015 at 23:03

    I'm unable to understand what exactly this code doing: exists $is_prime{$_} and $is_prime{$_}

    my %is_prime; @primes = grep { ( exists $is_prime{$_} and $is_prime{$_} ) or ( $is_prime{$_} = is_prime($_) ) } @numbers;

    I appreciate your time to read and answer and thank u in advance. :)

What editing mode am I in when interacting with a Perl script using OS X Terminal? Because the keyboard works differently to a normal shell.
4 direct replies — Read more / Contribute
by Cody Fendant
on Aug 03, 2015 at 21:42

    The following is a commonly-asked question, but please note it is not my question: "how do I get my keyboard to skip backward and forward using arrow keys in the OSX Terminal in normal circumstances?".

    My question is "how do I get my keyboard to skip backward and forward using arrow keys in the OSX Terminal when providing text input interactively to a perl script?".

    To explain, my Terminal does all of its arrowing between words and letters just fine, i.e. if I type like this at the command line (bash):

    codysmac: ~$ foo bar baz bax

    I can skip backward and forward a word at a time, a char at a time, to the start, to the end and so on.

    But when I'm interacting with a Perl script, this is no longer the case.

    Take this very simple script:

    print "foo bar bax baz\n"; print "is this correct?\n"; print "if not, type the correct version:\n"; my $new_version = <STDIN>;

    What "shell" or terminal type or other editing mode am I in if I start typing now? Because whatever it is, I can't use the arrow keys to go left and right, or any other shortcuts.

    I just get ^[[b and ^[[C for left and right.
TK Geometry question.
2 direct replies — Read more / Contribute
by kb3ien
on Aug 03, 2015 at 19:16
    I'd like to have a Canvas in a pane that 'fits' a window.

    The canvas has a preordained size, and should not be drawn any larger than 1000x400. Should it be truncated to fit the window that it should appear with scrollbars. I've come close by responding to the event and changing the size of the inner pane, but attempt to control the scrollbars seem to cause the subroutine to exit, and the image gets mangled.

    Can this layout be done without configuring elements on every change? > mwfOuter->configure( -scrollbars => $scrollbars); Here is the code:
    #!/usr/bin/perl use Data::Dumper; # this implements 5 text fields that detect the modified properly use strict; use Tk; use Tk::Pane; use Tk::Photo; use Tk::PNG; my $mw = MainWindow->new; $mw->configure(-menu => my $menubar = $mw->Menu); my $app = $menubar->cascade( -label => '~*' ) ; # TODO -bitm +ap =>); my $file = $menubar->cascade( -label => '~File'); my $edit = $menubar->cascade(-label => '~Edit'); my $go = $menubar->cascade(-label => '~Go'); my $group7; my @checkboxes ; my $messageBar = $mw->Entry( )->pack( -side=>"bottom" ) ; $mw->geometry('600x650'); our $lastWidth; our $lastHeight; my $frame = $mw->Canvas( )->form( -top => '20' , -bottom => [ '%100' +, -40 ] , -right => '%95' , -left => '%5' ); # dynamic ! my $mwfOuter = $frame->Scrolled('Pane', -scrollbars=>'osoe', -sticky=>'nwse', -background=>'white', -width => 1000+23, -height => 400+23 # actula dim )->pack(); my $colourBars = $mw->Photo ( -file => 'colourBars.png' ); my $stackImage = $mw->Photo ( -file => 'stack.png' ) ; my $mwf = $mwfOuter->Pane( -sticky=>'nwse', -width => 1000 , -height => 400 )->p +ack() ; # actual dim # this totally works, but you have to set the height of $mwf to fit t +he window , which the user can change.... my $label = $mwf->Label( -image => $colourBars )->place( -x => 0 , -y + => 0 ); $mw->bind( '<Configure>' => [ \&gotResized ] ) ; # we need to change +some things... I'd rather live this to Tk sub gotResized{ my $current_size = $mw->width . "x" . $mw->height; if ($lastWidth == $mw->width and $lastHeight == $mw->height ) +{ return (0==0); }; # the card area is 10% of the width, and height -60; # set the mwfOuter to that size warn $current_size; my $scrollbars; my $w = 1100; if ($mw->width < 1100 ) { # 1.1 * 1000 $w = int ($mw->width * 0.9 ) ; $scrollbars .= 'oe'; } my $h = 400 ; if ($mw->height < 460 ) { $w = int ($mw->height - 60) ; $scrollbars .= 'os'; }; warn "scrollbars $scrollbars "; #$mwfOuter->configure( -scrollbars => $scrollbars ); #TODO why + does this not work? if ($w > 50 and $h > 50 ) { warn "Wanting to resize to $w x $h"; $mwf->configure( -width => $w , -height => $h ) ; $lastWidth = $mw->width ; $lastHeight =$mw->height; #warn "Resized" . Dumper (@_) ; }; return (0==0); }; MainLoop();
Compilation error in the perl script
4 direct replies — Read more / Contribute
by shroh
on Aug 03, 2015 at 17:38
    hi Perl Experts, i am getting the compilation error while executing the script . Below is the code and errors that i am getting.
    #!C:\Perl\bin\perl.exe use strict; use warnings; # # This script is created to put the servers # in unplanned outage as part of the tasks that # are received to stop the monitoring on the servers # due to some maintenance activity on the servers. # Author : ROHIT SHARMA (INYROHS) my $path = 'E:/scripts/OutageNodes/'; require $path.'omwNodeDetails.pm'; &main(); sub main { my ($mode,@nodes); $mode=&get_mode(); @nodes=&get_node(); if( $mode eq 'enable'){ &enable_unplanned_outage(@nodes); } elsif($mode eq 'disable'){ &disable_unplanned_outage(@nodes); } else { &printLog("Error invalid Mode $mode");} # clear serverlist printLog ("Truncating serverlist"); open( SRV,'>',$path.'serverlist.txt') or die "Can't open SRV '$path.serverlist': $!"; close SRV; } sub get_mode { # expect values 'enable|disable' my $maintMode = lc $ARGV[0]; chomp($maintMode); if ($maintMode ne "enable") && ($maintMode ne "disable"){ $maintMode="error"; } return ($mainMode); } sub get_node { my ($sPath,$sFile,$sInfile,$sText, @sContent,@serverlist); $sPath="e:/scripts/Outage_nodes"; $sInFile=$sPath.'serverlist.txt'; ##checks if the file exists and pulls the info out if (-e "$sInFile"){ open(INFILE, "<$sInfile") or die "Can't open INFILE + '$sInfile': $!"; while (<INFILE>){ chomp; $sText="$_"; push(@sContent, $sText); } + close INFILE; }else{ &printLog("Error Cannot open $sInFile"); } # check serverlist had entries if (@sContent == 0){ printLog("ERROR No nodes found in $serverlist"); exit; } #get FQDN************ for my $NODE (@sContent){ my ($hostname) = split /\./, $NODE; my $fqdn = getNodeAttributes($hostname,'PrimaryNodeName'); if(length($fqdn) < 1) { printLog("No value returned from WMI, node ($NODE) doesn't ex +its in OMW."); next; } push(@serverlist,$fqdn); return(@serverlist); } sub enable_unplanned_outage { my ($FQDN,$mode,$cmd,@serverlist,$output); @sContent=@_[0..$#_]; foreach $FQDN (@sContent) { $cmd = "ovownodeutil.cmd -outage_node -unplanned -disable_heartb +eat -delete_msgs -node_name $FQDN -on "; printLog("Putting the server $FQDN into outage"); `$cmd`; printLog(`cmd`); } } sub disable_unplanned_outage { my ($FQDN, $mode, $cmd, $cmdresopcmona, @sContent,$output); @sContent = @_[0..$#_]; ####When the servers is brough out of maintenance the agent has to be +recycled to reset all the monitors. foreach $FQDN (@sContent) { $cmd = "ovownodeutil.cmd -outage_node -unplanned -disable_hear +tbeat -delete_msgs -node_name $FQDN -off "; printLog("Node $FQDN >>> off"); $cmdresopcmona = "ovdeploy -cmd \"ovc -restart opcmona\" -host $FQ +DN"; $output=`$cmd`; printLog($cmd); `$cmd`; printLog($output); printLog($cmdresopcmona); `$cmdresopcmona`; } } sub prinLog { my ($sPath, $logFile, $sOutFile, $sText, $date_time, $SEC, $MIN, +$HOUR, $DAY, $MON, $YEAR,$now); #get date/time $SEC, $MIN, $HOUR, $DAY, $MON, $YEAR = (localtime) [0..6]; $date_time = $YEAR + 1900 . $MON + 1 . $DAY . " " . $HOUR . ": +" . $MIN . ":" . $SEC; #get log file parameters $sPath = "e:\\scripts\\outage_nodes"; #review - + change to a standard location $logFile=$sPath."maintenanceMode_$date.log"; my ($logLine) = @_; my $now = sprintf "%02d:%02d:%02d",(localtime)[2,1,0]; open (LOG,'>>',$logfile) or die "Can't open LOG '$logfile': $! +\n"; print LOG "$now $logLine\n"; close LOG; }
    And the errors are
    E:\scripts\OutageNodes>perl outage_nodes.pl enable "my" variable $sPath masks earlier declaration in same statement at ou +tage_nodes .pl line 80. "my" variable $sPath masks earlier declaration in same scope at outage +_nodes.pl line 82. "my" variable $sText masks earlier declaration in same scope at outage +_nodes.pl line 95. "my" variable $now masks earlier declaration in same scope at outage_n +odes.pl li ne 212. syntax error at outage_nodes.pl line 62, near ") &&" Global symbol "$maintMode" requires explicit package name at outage_no +des.pl lin e 69. syntax error at outage_nodes.pl line 72, near "}" Missing right curly or square bracket at outage_nodes.pl line 231, at +end of lin e Execution of outage_nodes.pl aborted due to compilation errors.
Jenkins and Perl
2 direct replies — Read more / Contribute
by blue_cowdawg
on Aug 03, 2015 at 15:14

    I just discovered Jenkins and I'm having a blast with it having discovered all sorts of things I can do with it.

    Looking at the plethora of plugins available I discovered a couple of plugins having to do with Perl that don't seem to be documented. These are:

    • Perl Plugin
    • Perl Smoke Test Plugin
    Sadly there doesn't seem to be any documentation for them. Is there and I'm just not finding it?

    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; Blog: http://blog.berghold.net Warning: No political correctness allowed.
Perl CGI dynamic table cell
2 direct replies — Read more / Contribute
by alokranjan
on Aug 03, 2015 at 14:56
    Can anyone please let me know if I can use "if" condition with the value of my hash and then decide the color of the cell in the table?

    I am using Perl CGI to print my hash in table, but want to show the specific value say if it's less than 60, then cell color in red.

Unicode surrogate is illegal in UTF-8
1 direct reply — Read more / Contribute
by Rodster001
on Aug 03, 2015 at 14:14
    Hi Monks,

    I have some invalid utf-8. I want to catch the warning messages, and just un/redefine the string.

    For example:
    print Dumper $text; $VAR1 = { 'string' => "Text\x{daed}", }; print $text->{'string'}; 'Unicode surrogate U+DAED is illegal in UTF-8 at line 5.
    I've tried something like:
    local $SIG{__WARN__} = sub { print "WARNING!\n"; };
    Which catches the warning, but I lose context. I want to detect the warning then just set $text->{'string'} = "bad utf-8 encoding" or better yet, remove the offending character (regex?) so I end up with $text->{string} = "Text".

    Thanks for your help.
Perl solution for current batch file to extract specific column text
3 direct replies — Read more / Contribute
by oryan
on Aug 03, 2015 at 13:14

    I was in need of extracting a ton of data from an output file that is fairly systematic in nature so I wrote it as a batch file with a little help (I can hack my way through batch files, I'm definitely not an expert). The problem is there are 500,000 lines in the output file, several files to run the batch on and the batch takes several hours to run each time - not very efficient.

    I've seen things done in perl that are very fast, but I don't have any experience and I really don't know how to get it done. I assume there is no direct translator for batch->>perl, as that wouldn't really make sense. Any help would be fantastic:


    1. Find the string INTERPOLATED HYDROGRAPH

    2. Copy next data column to first column of new “Output.txt” (CAC40 in this case)

    3. Go down 6 rows and copy 2nd column (1223.) to column 2 of new “Output.txt”

    4. Go down 2 more rows (8 total) and copy 6th column (1456.) to columns 3 of new “Output.txt”

    5. repeat several thousand times


    SAMPLE OF INPUT FILE (text I need extracted in bold)

    *** *** *** *** ***


    blank line here


    6-HR 24-HR 72-HR 166.58-HR

    + (CFS) (HR)


    + 1223. 12.67 890. 588. 245. 106.

    (INCHES) .154 .408 .509 .509

    (AC-FT) 441. 1166. 1456. 1456.


    *** *** *** *** ***

    blank line here

    My super crazy slow and inefficient batch file solution (though it works) is:


    @echo off>output.txt & setlocal enabledelayedexpansion set input=input.txt rem this finds the text INTERPOLATED HYDROGRAPH in the input file rem sets k0 = to that line# rem sets x = to that line# + 6 and rem sets y = to that line# + 8 for /f "tokens=1,5 delims=[] " %%a in ('find /n "INTERPOLATED HYDROGRAPH"^<%input%') do ( set /a x=%%a+6 set k0=%%b echo line !x! set /a y=%%a+8 call :xx ) goto :eof :xx rem this line takes the line #s and extracts the following: rem 2nd column of line !x! and the 6th columns of line !y! rem find /n /v ""<%input%|findstr "^\[!x!\]" for /f "tokens=2 delims= " %%a in ('find /n /v ""^<%input%^|findstr "^\[!x!\] "') do set k=%%a for /f "tokens=6 delims= " %%a in ('find /n /v ""^<%input%^|findstr "^\[!y!\] "') do set k2=%%a rem this writes the values to a text file >>output.txt echo %k0% %k% %k2%

    Any help would be greatly appreciated, thanks.

remove lines that do not match search pattern
4 direct replies — Read more / Contribute
by jasonwolf
on Aug 03, 2015 at 09:56

    Folks: Been a while since I posted last, and I require a little pointing in the right direction - I am looking for a very simple solution, which removes lines that 'do not' match my criteria. I have a Expect script which dumps into a few generic devices, and logs out the session; however, I only want a few lines of the output. With the latter in mind - I have tried to fine tune my logging session for Expect; however, for some odd reason I must capture the entire session - otherwise nothing is captured. Due to the latter, I thought this would be a good exercise to learn more perl.

    Expect session output = logout.txt

    00:eb:99:33:bc:2c some string of text 00:eb:99:33:bc:2c Tx -.34 32423 00:eb:99:33:bc:2c null device log entries are empty - log service did not start 98:ab:34:12:ac:3c Rx critical Tx critical 00:eb:99:33:bc:2c device log entries are full 00:eb:99:33:bc:2c

    The output is not formatted any particular way due to embedded firmware. What I am hoping to do is remove the lines, which do not have a MAC address in them. I am thinking I can do something like 0-1|a-e: 0-1|a-e: 0-1|a-e: 0-1|a-e:~ To match the MAC address format. Looking for direction on how to do this - I have no clue where to start, or what to look for. Thank you JW

Tie::File, is unite file handle must?
1 direct reply — Read more / Contribute
by stm
on Aug 03, 2015 at 08:59


    This question is related to Tie::File module. Have opened a file and processing array functions. Then processing do while loop, here the script has to exit if conditions are met.

    Is it OK to use exit to exit the script without untie the file handle ? or any better solution available? last statement is not working here. It says an error "Can't "last" outside a loop block at". Copied few lines of my code to keep simple.

    tie my @in_array, 'Tie::File', $fileA, mode => O_RDWR or die $!; my $f_cnt = scalar(@in_array); my $retries; do { ##have removed lines for simplicity ## $retries++; if ($retries > 3) { print "3 attempts are failed.\n"; exit(); } } while ($f_cnt > 1 ); untie @in_array;

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!
  • 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.