[英]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? 我在Perl脚本中使用以下代码时遇到麻烦,请多多指教,如何更正语法?
# 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. 如果要在Perl中进行编码,请使用诸如Net :: Whois之类的模块。 Search CPAN for more such modules dealing with networking.
在CPAN中搜索有关网络的更多此类模块。 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 )
如果您只想使用不带模块的Perl,可以尝试一下(请注意,由于Perl拥有自己的grepping和字符串操作工具,因此您不必再使用egrep / awk)
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. 这利用了
open
的能力来打开管道。 The -|
-|
indicates the filehandle $pipe
should be attached to the output of the command. 指示文件句柄
$pipe
应该附加到命令的输出。 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. 这里的主要优点是您可以选择引用类型,
q[]
等效于单引号,并且没有插值,因此您不必转义。
But oh god, pasting an awk script into Perl is kind of silly and brittle. 但是,天哪,将awk脚本粘贴到Perl中有点愚蠢而脆弱。 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.
使用Net :: Whois之类的模块,或者在Perl中进行whois抓取,可能利用Email :: Find之类的优势,或者仅将其编写为bash脚本。 Your Perl script isn't doing much in Perl as it stands.
就目前而言,您的Perl脚本在Perl中的作用不大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.