2010-04-19 160 views
2

我在使用下面的代碼在我的Perl腳本中遇到了麻煩,任何建議真的很感激,如何更正語法?如何在Perl腳本中使用Awk?

# 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 

[email protected] 

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

#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$ 
+1

你不應該這樣做,但既然你是,你忘了逃避美元$我。 (下一次,仔細閱讀錯誤消息,你不必問這個問題。) – jrockway 2010-04-19 04:31:07

+1

另外,Perl被創建用來替換grep/sed/awk/...所以你應該只讀'whois'輸出和用Perl解析它。 – 2010-04-19 13:19:22

回答

4

如果您想在Perl中編寫代碼,請使用模塊,如Net::Whois。搜索CPAN以獲取更多與網絡相關的模塊。如果你想使用Perl的只是沒有一個模塊,你可以試試這個(注意,您不必使用的egrep/AWK了,因爲Perl有它自己的grepping和字符串處理設施)

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

最簡單的(儘管不是最流暢的)在Perl中使用awk的方式是a2p

echo 'your awk script' | a2p 
0

正如其他人提及的,反引號內插,所以其對$的跳閘。你可以逃避他們,或者你可以使用單引號,像這樣:

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

這需要的open的開管能力的優勢。 -|表示應將該文件句柄$pipe附加到該命令的輸出。這裏的主要優點是你可以選擇你的報價類型,q[]相當於單引號,而不是插值,所以你不必逃避的事情。

但是哦,將awk腳本粘貼到Perl中是一種愚蠢而脆弱的行爲。可以使用類似Net :: Whois這樣的模塊,也可以使用Perl中的Whois拼湊,可能利用諸如Email :: Find之類的東西,或者將其編寫爲bash腳本。您的Perl腳本在Perl中並沒有太多用處。