我在學習Perl,並且我有2個關於如何完成相同任務的例子,我只是對寫腳本的方式感到困惑。Perl函數和子程序
腳本#1
#!/usr/bin/perl
use strict;
use warnings;
use IO::File;
my $filename = "linesfile.txt"; # the name of the file
# open the file - with simple error reporting
my $fh = IO::File->new($filename, "r");
if(! $fh) {
print("Cannot open $filename ($!)\n");
exit;
}
# count the lines
my $count = 0;
while($fh->getline) {
$count++;
}
# close and print
$fh->close;
print("There are $count lines in $filename\n");
腳本#2
#!/usr/bin/perl
#
use strict;
use warnings;
use IO::File;
main(@ARGV);
# entry point
sub main
{
my $filename = shift || "linesfile.txt";
my $count = countlines($filename);
message("There are $count lines in $filename");
}
# countlines (filename) - count the lines in a file
# returns the number of lines
sub countlines
{
my $filename = shift;
error("countlines: missing filename") unless $filename;
# open the file
my $fh = IO::File->new($filename, "r") or
error("Cannot open $filename ($!)\n");
# count the lines
my $count = 0;
$count++ while($fh->getline);
# return the result
return $count;
}
# message (string) - display a message terminated with a newline
sub message
{
my $m = shift or return;
print("$m\n");
}
# error (string) - display an error message and exit
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
從腳本#2我不明白背後的以下
- 主(@ARGV)的目的;
- 爲什麼我們需要子消息和子錯誤?
由於