在子例程中传递全局变量的值

Passing the value of a global variable inside a subroutine

下面是我写的代码片段,这里的问题是 $server 变量不能在子程序中传递。如何在子例程中传递全局变量的值。请帮忙!

    use strict;
    use warnings;

    my (@list,$server);

    @list = qw/server1.net server2.net server3.net/;

    foreach $server(@list) {
    #calling sub-routines
    command1(); 
    command2();
    }

    sub command1 {
    print $server;
    system("command1");
    }

    sub command2 {
    print $server;
    system("command2");
    }

..如果你想使用全局变量:

our $server;
my (@list);

... rest of the code ...

或者当你想保留它的词法时,另见

use strict;
use warnings;


my (@list, $server);

@list = qw/server1.net server2.net server3.net/;

foreach (@list) {
  $server = $_;   # <<-- use it this way
  #calling sub-routines
  command1();
  command2();
}

sub command1 {
  print $server;
  system("command1");
}

sub command2 {
  print $server;
  system("command2");
}

首选:作为参数传递:

use strict;
use warnings;

my (@list);

@list = qw/server1.net server2.net server3.net/;

foreach my $server(@list) {
  #calling sub-routines
  command1($server);
  command2($server);
}

sub command1 {
  my ($server) = @_;
  print $server, "\n";
  system("command1");
}

sub command2 {
  my ($server) = @_;
  print $server, "\n";
  system("command2");
}

好的编程最重要的规则之一是减少coupling。减少一段代码对其他代码段的依赖性可以提高可读性、可维护性并减少出错的机会。

你的潜艇不应该依赖于声明和可用的全局变量。潜艇应该有一个服务器参数。

出于同样的原因,您还应该将变量的范围限制在需要的地方。

use strict;
use warnings;
use feature qw( say );

sub command1 {
   my ($server) = @_;
   say $server;
   system("command1", $server);
}

sub command2 {
   my ($server) = @_;
   say $server;
   system("command2", $server);
}

{
   my @servers = qw( server1.net server2.net server3.net );

   for my $server (@servers) {
      command1($server); 
      command2($server);
   }
}