我新的Perl和想模仿的grep -n是這樣的:perl模擬grep -n?
想:
# egrep -n 'malloc\(|free\(|printf\(' test.c
5:p = malloc(sizeof(char));
6:printf("Test\n");
7:free(p);
有:
# perl grep.pl test.c
malloc\(line 7
free\(line 7
printf(
Processed 10 lines
腳本:
#!/usr/bin/perl
$verbose = 1;
@pattern = ('malloc\(', 'free\(', 'printf(');
$counter = 0;
open(FH, "<", $ARGV[1]) or die;
while (<>) {
my $matches = (@pattern[0-2]);
$counter++;
# print "line $counter:$_" if ($_ =~ /malloc\(/o);
print join("line $counter\t\n",@pattern),"\n" if ($_ =~ /$matches/o);
close (FH);
}
print "\n";
$verbose == 1 && print "Processed $counter lines\n";
不知何故,計數器是錯誤的。我在這裏錯過了什麼?
什麼是閉環(FH)在循環內部執行? – Mat 2012-01-14 16:41:05
開頭(FH,「<」,$ ARGV [1])'首先是什麼,因爲讀取是從<<>而不是''完成的? –
2012-01-14 16:57:40
爲什麼downvotes?問題是明確的,並且已經顯示出努力。我想知道的唯一事情就是OP爲什麼要首先做到這一點。 – Zaid 2012-01-14 19:54:26