perl 传递一个count变量($#)是如何获得完整数据的引用的?

t98cgbkg  于 2023-06-23  发布在  Perl
关注(0)|答案(2)|浏览(117)

下面是我的代码:

sub print_list {
  $max = $_[0];
  for ($i=0; $i<$max; $i++)
  {
    print "$i.  $list[$i][0]\t $list[$i][1]\n";
  }
}

# Declaring a 2-D Array, which is just an array of 1-D arrays

@list = ( ["vi   ", "Null"], ["emacs", "Null"], ["joe  ", "Null" ]);

$max = $#list + 1;

print "Initial Values\n";
print_list($max);

print "\n\n";

输出:-

Initial Values 
 0. vi                 Null 
 1. emacs           Null 
 2. joe               Null

在上面的代码中,$max是如何传递给一个函数的?

qkf9rpyu

qkf9rpyu1#

$max传递到函数中不会同时将@list数组传递到函数中。通过什么都不传递来证明这一点:

sub print_list {
  for ($i=0; $i<$max; $i++)
  {
    print "$i.  $list[$i][0]\t $list[$i][1]\n";
  }
}

# Declaring a 2-D Array, which is just an array of 1-D arrays

@list = ( ["vi   ", "Null"], ["emacs", "Null"], ["joe  ", "Null" ]);

$max = $#list + 1;

print "Initial Values\n";
print_list();

print "\n\n";

@list数组变量是全局变量。
perldoc perlsub

sbtkgmzw

sbtkgmzw2#

@list数据根本没有传递到子例程中。您可以通过@list的相同版本访问它,该版本在子例程外部可见。访问没有传递到子例程中的变量是一个非常糟糕的主意,因为子例程与调用它的代码耦合得太紧了。例如,在代码中,print_list只能作用于名为@list的变量。如果你把数组传递给子程序,那么它的名字就不重要了。

# I've renamed this as you're dealing with arrays, not lists
sub print_array {
  my $length = shift;
  my @array  = @_;

  for ($i = 0; $i < $max; $i++) {
    print "$i.  $array[$i][0]\t $array[$i][1]\n";
  }
}

my @editors = ( ["vi   ", "Null"], ["emacs", "Null"], ["joe  ", "Null" ]);
my $number_of_editors = @editors; # More readable than $#editors + 1

print_array($number_of_editors, @editors);

但是你根本不需要将数组长度传递给子例程。

# I've renamed this as you're dealing with arrays, not lists
sub print_array {
  my @array  = @_;

  for ($i = 0; $i < @array; $i++) {
    print "$i.  $array[$i][0]\t $array[$i][1]\n";
  }
}

my @editors = ( ["vi   ", "Null"], ["emacs", "Null"], ["joe  ", "Null" ]);

print_array(@editors);

作为最后的改进,foreach循环几乎总是比C风格的for循环更容易遵循

# I've renamed this as you're dealing with arrays, not lists
sub print_array {
  my @array  = @_;

  foreach (0 .. $#array) {
    print "$_.  $array[$_][0]\t $array[$_][1]\n";
  }
}

相关问题