
FishMonger
Veteran
Oct 6, 2008, 9:19 AM
Post #18 of 19
(1851 views)
|
|
Re: [maestria] Perl file handle
[In reply to]
|
Can't Post
|
|
Here is my version. Give the file name as the argument for the script. Ex: perl filename.pl myfile.txt #!/usr/bin/perl -l while(<>){ @arr=split(/ /); foreach (@arr){ $count++; } } print $count; How about showing beginners how to write quality code?
#!/usr/bin/perl use warnings; use strict; die "Filename not passed\n" unless @ARGV; chomp(my $inFileName = shift); # I'd need to do a benchmark test, but this is probably the most efficient. my $words = (split /\s+/, `wc $inFileName`)[2]; print "Words:$words\n"; # However, this one doesn't use an external utility. my $count; open my $FILE, '<', $inFileName or die "can't open '$inFileName' $!"; while ( <$FILE> ) { $count++ for split; } print $count,$/; [edit] In my test, the wc command extracted the count of words, lines, and characters. When I posted, I simply altered the array slice to return only the word count. The command itself could be altered accordingly, if desired.[/edit]
(This post was edited by FishMonger on Oct 6, 2008, 9:27 AM)
|