dotplan

troubleshooting & performance analysis

Perl

String Equality

Testing for string equality uses ‘eq’ NOT ‘==’ e.g.
if ($build eq 'mainng') {

Splitting fields

    Split fields space delimited line, use “/ +/”:


e.g.
@fields=split/ +/,$data_line;
$the_first_field=$fields[1]

Reading files

    Opening and reading a file specified on command line


use Getopt::Std;
our($opt_f);
getopt('f');
my $inputfile=$opt_f;
open (IN,$inputfile);
while ('<'IN&gt){
$line=$_;
#Do some processing on each line here.
}
 

Usage / Option processing

There are two forms of getting command line arguments in perl. Firstly getopt

getopt(bmpturvzag);

In this form every option takes an argument. This form does not allow you to have a switch without an argument e.g. one cannot have -v, it would have to be '-v 1'

getopts('b:m:p:t:u:r:vz:a:g');

This form allows either switch e.g. '-v' or an option with an argument '-d 1' The difference is specified with the ':' after the switch letter in the getopts() argument list.

Check that all required options are present before moving on

getopt('fdsj');

#
# Check that we have all the options that are required, else give
# usage and exit.
#
if ( ! ($opt_f && $opt_d && $opt_s && $opt_j) ) {
usage();
}

Then use a simple qq{ string to print out a usage message

sub usage {
my $usage = qq{ Usage
-f Filertype e.g. FAS2020, FAS2050, SV550
-j jumps, number of 'spans' that are written to
-d Density e.g. 95pct, 80pct
-s A list of Sims e.g 128,64,32,16
};

print $usage;
exit 1;
}

Substr

Assign the result of substr to a new variable. This example returns the first 4 chars (i.e 4 chars from position 0 onwards) of the string $runid and assigns the result to $rundate.

my $rundate=substr $runid,0,4;

Leave a Reply

*

© 2009 dotplan. All Rights Reserved.

This blog is powered by Wordpress and Magatheme by Bryan Helmig.