{
my ($infile, %wordhash) = @_;
......
}
{
my (%wordhash, $infile) = @_;
......
}
{
my ($outfile, $wordhash) = @_;
open OUT, ">$outfile" or die "cannot open file $outfile";
my @array = sort { $wordhash->{$b}<=>$wordhash->{$a}} keys %$wordhash;
# 这里只能用$wordhash->{$b},而不能写成 $wordhash{$b}
for (my $i = 0; $i<@array; $i++)
{
print OUT $array[$i]," ",$wordhash->{$array[$i]},"/n";
}
close OUT;
}
如果子函数需要返回,也是一样的:
my %ophash;
*ophash = count_word(/%ophash, $filename);
sub count_word
{
my ($wordhash, $infile) = @_;
open IN, "<$infile" or die "cannot open file $infile";
my $text = <IN>;
close IN;
my @array = split(//s/,$text);
for (my $i=0; $i<@array; $i++)
{
$wordhash->{$array[$i]}++;
}
return ($wordhash);
}
同理,如果要传多个array:
processarrays(/@array1, /@array2);
$sub processarrays{
my($a1, $a2) = @_;
foreach(@$a1){ # dereferences $a1
print $_;
}
for($i=0; $i<@$a2; $i++){
print $a2->[$i]; #get at a particular index within array
}
}
三。
如果不是有特别需要的话,呼呼,还是直接定义为全局变量,而不传递是最方便的啦。:P
文章来源: http://mzhangbj.spaces.live.com/blog/cns!6581afdaae0ec2e3!243.entry