以下代码显示错误,请帮助我解决代码中的错误
package My::count
use Exporter qw(import);
our @Export_ok=qw(line_count);
sub line_count {
my $line=@_;
return $line;
}
我将上面的代码保存在count.pm
中use My::count qw(line_count);
open INPUT,"<filename.txt";
$line++;
print line count is $line \n";
我将此文件保存在a.pl
中答案 0 :(得分:1)
让我们详细看一下这段代码。
# There's a typo on the line below. It should be /usr/bin/perl
#!usr/bin/perl
# Never comment out these lines.
# Instead, take the time to fix the problems.
# Oh, and it's "warnings", not "warning".
#use strict;
#use warning;
# Always check the return value from open()
# Please use lexical filehandles.
# Please use three-arguments to open().
# open my $ip_fh, '<', 'test1.txt' or die $!;
open IP,"<test1.txt";
my ($line_count,$word_count)=(0,0);
# You're rather fighting against Perl here.
# If you do things in a Perlish manner then it all becomes easier
while(my $line=<IP>) {
$line_count++;
my @words_on_this_line= split(" ",$line);
$word_count+= scalar(@words_on_this_line);
}
print"This file contains $line_count lines\n";
print"this file contains $word_count words\n";
# It all goes a bit wrong here. You don't have an array called @IP.
# I think you wanted to iterate across the file again.
# Either use seek() to return to the start of the file, or store
# the lines in @IP as you're reading them.
# Also, you need to declare $line.
foreach $line(@IP) {
if ($line =~ /^>/) {
print $line;
}
}
close IP;
我会做这样的事情。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010; # for say()
my $filename = shift || die "Must give file name\n";
open my $fh, '<', $filename or die "Can't open $filename: $!\n";
my ($word_count, @matches);
while (<$fh>) {
# By default, split() splits $_ on whitespace
my @words_on_line = split;
$word_count += @words_on_line;
push @matches, $_ if /^>/;
}
# No need to count lines, Perl does that for us (in $.)
say "This file contains $. lines";
say "This file contains $word_count words";
print @matches;