开发者

How can I use Awk inside a Perl script?

I'm having trouble using the following code inside my Perl script, any advise is really appreciated, how to correct the syntax?

# If I execute in bash, it's working just fine

bash$ whois google.com | egrep "\w+([._-]\w)*@\w+([._-]\w)*\.\w{2,4}" |awk ' {for (i=1;i<=NF;i++) {if ( $i ~ /[[:alpha:]]@[[:alpha:]]/ )  { print $i}}}'|head -n1

contact-admin@google.com

#-----------------------------------

#but this doesn't work 

bash$ ./email.pl google.com
awk:  {for (i=1;i<=NF;i++) {if (  ~ /[[:alpha:]]@[[:alpha:]]/ )  { print }}}
awk:                              ^ syntax error

# Here is my script
bash$ cat email.pl 
####\#!/usr/bin/perl         


$input = lc shift @ARGV;

$host = $input开发者_JAVA百科;

my $email = `whois $host | egrep "\w+([._-]\w)*@\w+([._-]\w)*\.\w{2,4}" |awk ' {for (i=1;i<=NF;i++) {if ( $i ~ /[[:alpha:]]@[[:alpha:]]/ )  { print $i}}}'|head -1`;
print my $email;

bash$


use a module such as Net::Whois if you want to code in Perl. Search CPAN for more such modules dealing with networking. If you want to use just Perl without a module, you can try this (note you don't have to use egrep/awk anymore, since Perl has its own grepping and string manipulation facilities )

   open(WHOIS, "whois google.com |")    || die "can't fork whois: $!";
   while (<WHOIS>) {

       print "--> $_\n";  # do something to with regex to get your email address
   }            
   close(WHOISE)                      || die "can't close whois: $!";


The easiest (though not the smoothest) way to use awk inside Perl is a2p.

echo 'your awk script' | a2p


As mentioned by others, backticks interpolate, so its tripping on the $'s. You could escape them all, or you could use single quotes like so:

open my $pipe, "-|", q[whois google.com | egrep ... |head -n1];
my $result = join "", <$pipe>;
close $pipe;

This takes advantage of open's ability to open a pipe. The -| indicates the filehandle $pipe should be attached to the output of the command. The chief advantage here is you can choose your quoting type, q[] is equivalent to single-quotes and not interpolated so you don't have to escape things.

But oh god, pasting an awk script into Perl is kind of silly and brittle. Either use a module like Net::Whois, or do the whois scraping in Perl, possibly taking advantage of things like Email::Find, or just write it as a bash script. Your Perl script isn't doing much in Perl as it stands.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜