Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Different behaviours in the similar scripts

by shroh (Acolyte)
on Aug 06, 2015 at 20:55 UTC ( [id://1137751]=perlquestion: print w/replies, xml ) Need Help??

shroh has asked for the wisdom of the Perl Monks concerning the following question:

Hi Experts, I had one script which was workfectly fine but had only few subroutines which i can not use in the enterprise due to some restrictions, They need me to put the entire script within the "main" subroutine and call the other subroutine from that. To some extent the new script is working but its not giving me the desired results.Below is the old script.
#!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'; # expect values 'on|off' my $maintMode = lc $ARGV[0] || ''; chomp($maintMode); unless ($maintMode =~ /^(on|off)$/){ die "Invalid mode $maintMode\n"; } # date/time my ($SEC,$MIN,$HOUR, $DAY, $MON, $YEAR)= (localtime) [0..6]; my $date = sprintf "%04d_%02d_%02d",$YEAR+1900,$MON+1,$DAY; my $time = sprintf "%02d:%02d:%02d",$HOUR,$MIN,$SEC; # log file my $logfile = $path . "maintenanceMode_$date.log"; open (LOG,'>>',$logfile) or die "Can't open LOG '$logfile': $!\n"; printLog ("\n=================== Date is $date Time is $time Starting the maintenance mode process to turn $maintMode outages."); # server file my $serverlist = $path.'serverlist.txt'; open( SRV,'<',$serverlist) or die "Can't open SVR '$serverlist': $!"; my @nodes = (); while (<SRV>){ #This code is to remove any white spaces from the serve +r list. # skip blank lines s/\s+$//; s/^\s+//; next if /^$/; # Validate records, it will make sure no unwanted characters are ent +ered in server list. #if (/[A-Za-z0-9_]/){ push @nodes,$_; #} else { #printLog("ERROR Invalid record '$_'"); #} } # check serverlist had entries if (@nodes == 0){ printLog("ERROR No nodes found in $serverlist"); exit; } # process each node for my $NODE (@nodes){ 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; } # command common to on/off my $cmd = "ovownodeutil.cmd -outage_node -unplanned -disable_heartbe +at -delete_msgs -node_name $fqdn -$maintMode "; printLog("Node $hostname >>> $maintMode"); my $output=`$cmd`; # on command or off commands if ( $maintMode eq 'on' ){ printLog($cmd); `$cmd`; printLog($output); } elsif( $maintMode eq 'off' ){ printLog("Bringing the server $NODE out of outage."); ###################################################################### +##### # If a node is leaving maintenance mode, the agent has to be recycled. # This will "reset" the monitors to re-alert if they are in an error s +tate # my $cmdresopcmona="ovdeploy -cmd \"ovc -restart opcmona\" -host $f +qdn"; my $cmdresopcle ="ovdeploy -cmd \"ovc -restart opcle\" -host $fqd +n"; printLog($cmd); `$cmd`; printLog($output); # printLog($cmdresopcmona); # `$cmdresopcmona`; # printLog($cmdresopcle); # `$cmdresopcle`; } } # clear serverlist printLog ("Truncating $serverlist"); open( SRV,'>',$serverlist) or die "Can't open SRV '$serverlist': $!"; close SRV; # end close LOG; # screen and log sub printLog { my ($logLine) = @_; my $now = sprintf "%02d:%02d:%02d",(localtime)[2,1,0]; print "$logLine\n"; print LOG "$now $logLine\n"; }
In the above script i am splitting the server name like this my ($hostname) = split /\./, $NODE; where $NODE will be in the form of servername.something.com and $hostname will be servername But in the new script i am trying to do the same thing in the get_node subroutine but its not giving the desired result .Below is the new script.
#!C:\Perl\bin\perl.exe use strict; use warnings; #use diagnostics; # # 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 $path = 'E:/scripts/OutageNodes/'; require $path.'omwNodeDetails.pm'; #my ($mode,@nodes); my $mode=get_mode(); my @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 $maintMode; } sub get_node { #my ($sPath,$sFile,$sInFile,$sText, @sContent,@serverlist,$hostname,$f +qdn); my $sPath='e:/scripts/OutageNodes/'; my $sInFile=$sPath.'serverlist.txt'; my @sContent=(); my $sText; ##checks if the file exists and pulls the info out if (-e "$sInFile"){ 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.txt"); exit; } #get FQDN************ my $hostname; my $fqdn; my @serverlist; for my $NODE (@sContent){ $hostname = split /\./, $NODE; $fqdn = getNodeAttributes($hostname,'PrimaryNodeName'); printLog($fqdn); printLog($hostname); if(length($fqdn) < 1) { printLog("No value returned from WMI, node ($NODE) doesn't ex +ists in OMW."); next; } push(@serverlist,$fqdn); } return(@serverlist); } sub enable_unplanned_outage { #my ($FQDN,$cmd); my @nodelist=@_[0..$#_]; foreach my $FQDN (@nodelist) { my $cmd = "ovownodeutil.cmd -outage_node -unplanned -disable_he +artbeat -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); my @sContent = @_[0..$#_]; ####When the servers is brough out of maintenance the agent has to be +recycled to reset all the monitors. foreach my $FQDN (@sContent) { my $cmd = "ovownodeutil.cmd -outage_node -unplanned -disable_h +eartbeat -delete_msgs -node_name $FQDN -off "; printLog("Node $FQDN >>> off"); my $cmdresopcmona = "ovdeploy -cmd \"ovc -restart opcmona\" -host +$FQDN"; my $output=`$cmd`; printLog($cmd); `$cmd`; printLog($output); printLog($cmdresopcmona); `$cmdresopcmona`; } } sub printLog { #my ($sPath, $logFile, $sOutFile, $sText, $date_time, $SEC, $MIN, $ +HOUR, $DAY, $MON, $YEAR,$now,$logLine,$now); #get date/time my($SEC, $MIN, $HOUR, $DAY, $MON, $YEAR) = (localtime) [0..6]; my $date_time = $YEAR + 1900 . $MON + 1 . $DAY ; #get log file parameters my $sPath = "e:\\scripts\\OutageNodes\\"; #revi +ew - change to a standard location my $logFile=$sPath."maintenanceMode_$date_time.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; }
Here $hostname = split /\./, $NODE; $hostname returns a number instead of the servername. In both the cases the input file remains the same. Any help is highly appreciated.

Replies are listed 'Best First'.
Re: Different behaviours in the similar scripts
by stevieb (Canon) on Aug 06, 2015 at 21:04 UTC

    You said:

    "In the above script i am splitting the server name like this my ($hostname) = split /\./, $NODE;"

    But in the new script, you don't assign $hostname the same way:

    $hostname = split /\./, $NODE;

    You need to put parens () around $hostname like you have in the first script. From perldoc -f split:

    "Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context."

    Which means that using a scalar instead of a list on the left-hand side, it'll return the number of items returned from the split. ($hostname) is retrieving in list context, whereas $hostname is looking for the scalar return.

    Also, you're still not properly indenting. I highly recommend spending the few minutes it would take to go through the entire script and indent it consistently.

      Thanks Steive, It is working now. Identation is a big problem for me. I am very poor in the basics of the indentation like which braces will come when.. Do you have any guide which has some documentation on how to do that.
        You can use perltidy to cleanup the formatting.
        "Do you have any guide which has some documentation on how to do that."

        As part of the core documentation which comes with Perl: perlstyle - Perl Style Guide.

        — Ken

        It depends a bit on whether your bosses have a syntax style that you must follow. If you are free to choose, I suggest paying attention to the syntax of the Perl code you read on this site, and also the source of modules you use. You should find that one style or another is easiest for you to read and understand, and that should be the basis of the choice.

        See this article for some examples of formal styles.

        The way forward always starts with a minimal test.
Re: Different behaviours in the similar scripts
by Corion (Patriarch) on Aug 06, 2015 at 21:06 UTC

    The difference is in the parentheses:

    my ($hostname) = split /\./, $NODE;

    versus

    $hostname = split /\./, $NODE;

    The first statement, with the parentheses, means that the left-hand side is a list, and thus the right-hand side is evaluated in list context and the first element of the list gets assigned to $hostname.

    The second statement, without the parentheses, means that the left-hand side is a scalar, and thus the right-hand side is evaluated in scalar context and returns the number of elements. That is the number you then see in $hostname.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1137751]
Approved by 2teez
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-19 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found