perl - Why I can't pass one argument to sub -
input directory name , output text file name in directory , file's name, line count, word count. when checked program, know when second sub working, $_ nothing "".
how should fix ?
#!/usr/bin/perl use strict; use warnings; $dir = <stdin>; chomp($dir); # remove '\n'(new-line character) directory address opendir(dirhandle, "$dir"); @arr = readdir(dirhandle); close(dirhandle); foreach(@arr){ if($_ =~ /.txt/){ print "file name : $_\n"; $tmp = $_; print "line numb : ".&how_many_lines($_)."\n"; print "word numb : ".&how_many_words($_)."\n\n"; } } sub how_many_lines{ open(file, "$_") || die "can't open '$_': $!"; $cnt=0; while(<file>){ $cnt++; } close(file); return $cnt; } sub how_many_words{ open(text, "$_") || die "can't open '$_': $!"; # error! printed "can't open ''" : no such file or directory $cnt=0; while(<text>){ @tmp = split(/ /, $_); $num = @tmp; $cnt += $num; } close(text); return $cnt; }
you cannot refer first argument of sub $_. should $_[0], first element of array @_, list of arguments.
the idiomatic (not confused idiotic) way of retrieving arguments in sub this:
my $filename = shift; # shift uses @_ automatically without arguments perl allows same names scalars, arrays , hashes: $foo, @foo, %foo different entities. when index array @foo zero, becomes $foo[0]. not same $foo.
Comments
Post a Comment