Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Blog | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

stupid perl question.



> Why doesn't this work?

I took your code and ran it, and here are some answers:

> What it's doing up dumping the output to the console and not
> assigning it to 
> $ipaddy.
 
It *is* assigning the output to $ipaddy.  The output is showing up on
the console because of your 'print' statement.  No print, no output.

The reason you're not getting the output you expect is because you
forgot to escape the '$3' in your awk command string.  That means that
perl is doing variable substitution on '$3' before awk ever gets to
to see it.

It will work as expected if you were to write it like this:

my $ipaddy = `/sbin/ifconfig \\
                | grep Bcast  \\
                | sed \'s/:/ /g\' \\
                | awk \'{print \$3}\'`;

Notice the backslash before hte '$3'.  I've also split it across
several lines for greater readability in the face of mail clients that
wrap long lines.

This works...but that being said, I agree with the other poster that
this is a silly way of getting what you want.

(1) If you ever find yourself piping grep into awk, you've already
wasted one program execution.  Awk performs regular expression
matching, so:

  /sbin/ifconfig eth0 | sed 's/:/ /' | awk '/Bcast/ {print $3}'

This is just a pet peeve of mine, but still isn't a very good solution.

(2) In the end, perl can do all the patching matching and field
extraction that you want, so why bother with all the above?  Try this:

  ($ipaddy) = `/sbin/ifconfig eth0` =~ /inet addr:([\d\.]+)/

The '=~' operator binds the output of the backtick block to the
following regular expression.  In a list context, the 'm//' operator
"returns a list consisting of the subexpressions matched by
parentheses in the pattern" (from 'perldoc perlop')., and our regular
expression has one set of parentheses, which matches the ipaddress,
which gets assigned to $ipaddy.

> #!/usr/bin/perl
> 
> my $ipaddy = `/sbin/ifconfig | grep Bcast | sed \'s/:/ /g\' | awk
> \'{print 
> $3}\'`;
> chomp $ipaddy;
> print $ipaddy;



=====
lars at larsshack.org --> http://www.larsshack.org/

__________________________________________________
Do You Yahoo!?
Find a job, post your resume.
http://careers.yahoo.com




BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org