How can I use Awk inside a Perl script?
I am having trouble using the following code inside my Perl script, any advice really appreciated how to fix the syntax?
# If I execute in bash, it 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$
a source to share
use a module like Net :: Whois if you want to inject code into Perl. Search CPAN for more such network related modules. If you only want to use Perl without a module, you can try this (note that you don't need to use egrep / awk anymore as Perl has its own link and line controls)
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: $!";
a source to share
As others mentioned, backticks are interpolated, so its firing on $
. You could escape them all, or you could use single quotes like this:
open my $pipe, "-|", q[whois google.com | egrep ... |head -n1];
my $result = join "", <$pipe>;
close $pipe;
This allows you to use the open
ability to open the channel. -|
indicates that the file descriptor $pipe
should be appended to the output of the command. The main advantage here is that you can choose your own quote type, it is q[]
equivalent to single quotes and is not interpolated, so you have nothing to hide.
But god, embedding awk script in Perl is silly and fragile. Either use a module like Net :: Whois, or flush whois in Perl, perhaps using things like Email :: Find, or just write it as a bash script. Your Perl script doesn't do much in Perl as it costs.
a source to share