【发布时间】:2011-12-13 23:35:24
【问题描述】:
我在下面为我的任务创建了这个脚本。它要求一个文本文件,检查单词的频率,并列出出现次数最多的 10 个单词。一切正常,但我需要这个脚本能够通过命令行和标准输入启动。
所以我需要能够编写“perl wfreq.pl example.txt”,这应该启动脚本而不是询问文本文件的问题。我不确定如何真正做到这一点。我想我可能需要一个 while 循环,如果你在终端命令行上给它一个文本文件,它会跳过 STDIN。
我该怎么做?
脚本
#! /usr/bin/perl
use utf8;
use warnings;
print "Please enter the name of the file: \n" ;
$file = <STDIN>;
chop $file;
open(my $DATA, "<:utf8", $file) or die "Oops!!: $!";
binmode STDOUT, ":utf8";
while(<$DATA>) {
tr/A-Za-z//cs;
s/[;:()".,!?]/ /gio;
foreach $word (split(' ', lc $_)) {
$freq{$word}++;
}
}
foreach $word (sort { $freq{$b} <=> $freq{$a} } keys %freq) {
@fr = (@fr, $freq{$word});
@ord = (@ord, $word);
}
for ($v =0; $v < 10; $v++) {
print " $fr[$v] | $ord[$v]\n";
}
【问题讨论】:
标签: perl command-line stdin