[wellylug] perl hacking

Grant McLean grant at mclean.net.nz
Thu Apr 14 22:44:38 NZST 2005


Hmm

Without knowing exactly what the output of that snmpwalk command looks
like, it's a bit hard to say.  It looks to me like your Perl code and
awk code are trying to grab bits of the output in slightly different
ways and the Perl code probably isn't doing what the author intended
anyway.


>  snmpwalk -v 2c $host -c community hrStorageAllocationUnits.$drive|awk
> '{print $4}'

That awk snippet will replace each line with the contents of the fourth
'field' where fields are delimited by whitespace.  That's pretty
straightforward, but the Perl code is doing something entirely
different.



> sub getblocksize {
>    $blocksize=`snmpwalk -v 2c $host -c $community hrStorageAllocationUnits.$drive 2>/dev/null`;

That code slurped in the output of snmpwalk.  
Was it one line of output or multiple lines (one per drive?).  
The next line seems to assume it's one line:

>     ($name,$blocks)=split(/ = /, chomp($blocksize));

This looks like a bug.  I'd guess that the chomp was intended to discard
the last newline and the split is meant to operate on the chomped
result.  But chomp actually modifies the named argument and returns the
number of characters chomped.  '1' in this case.  

The split is then trying to use the string ' = ' as a delimiter to split
the line into fields and store the first two fields in $name and $block.
Unfortunately the string '1' doesn't contain any ' = ' so $name ends up
containing '1' and $blocks ends up undefined.

>     $blocks=&splitnamevalue($blocksize);

This is taking the original output from snmpwalk (minus the chomped
trailing newline)  and passing it to another subroutine.  From the name
I'd guess it's going to do something similar to what the failed split
command above was trying to do.  The return value from the subroutine is
overwriting that '1' we stored in $ blocks a moment ago.

>     $blocks=~s/\ .*//;

This seems to be discarding the first whitespace character and anything
that follows it.

>     return $blocks;

If all you want is the fourth field then try this:

my $data = `snmpwalk -v 2c $host -c $community
hrStorageAllocationUnits.$drive 2>/dev/null`;

my @fields = split(/\s+/, $data);
return $fields[3];

The array index is '3' since Perl arrays number from 0.  Whether that's
any use to you I don't know.

If you're looking to improve your Perl, might I suggest coming along to
Perl Mongers? (http://wellington.pm.org/)

Cheers
Grant





More information about the wellylug mailing list