简体   繁体   中英

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;

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: $!";

在Perl中使用awk的最简单(尽管不是最流畅)的方法是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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM