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

时间:2018-07-08 15:04:46

标签: perl subroutine

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

event.clientX

2 个答案:

答案 0 :(得分:1)

良好编程的最重要规则之一是减少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);
   }
}

答案 1 :(得分:-1)

..如果要使用全局变量:

our $server;
my (@list);

... rest of the code ...

,或者当您想保留其词汇时,另请参见Perl foreach loop variable scope

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");
}