全局变量,Perl中的子程序变量问题 [英] Global Variable, subroutine variable Question in Perl

查看:243
本文介绍了全局变量,Perl中的子程序变量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  sub foo()如何将子程序变量值转换为另一个子程序变量,我可以使用全局变量。 {

my $ myvar =你好;
}

sub foo1(){
my $ myvar1 = $ myvar; #我如何从$ myvar获得Hello。
}

我尝试使用包和全局变量,但失败了。

 软件包栏; 
我们的$ bar;

谢谢。

解决方案

  {my $ myvar $ 

你可以在包含2个函数的作用域中声明该变量: b
$ b sub foo {
$ myvar =Hello;
}

sub foo1 {
my $ myvar1 = $ myvar;




$ b $ p
$ b

虽然这不是很优雅,但可能很难因为在 foo1 中设置 $ myvar 的值时不清楚。

  sub foo {
my $ myvar =Hello ;
返回$ myvar;
}

sub foo1 {
my($ myvar)= @_;
my $ myvar1 = $ myvar;
}

#调用代码
my $ myvar = foo();
foo1($ myvar);

请注意,所有3 $ myvar 是不同的变量,在不同的范围。



作为一个方面说明,使用原型( sub foo())可能不是一个好主意,除非你真的知道他们在做什么,这可能并非如此(参见关于原型讨论原型的问题

How can I transfer the subroutine variable value into another subroutine variable, Can I use global variable.

sub foo(){

my $myvar = "Hello";
} 

sub foo1(){
my $myvar1 = $myvar;   # how can I get the "Hello" from $myvar.
}

I tried to use package and global variable, but failed.

Package Bar;
our $bar;

Thank you.

解决方案

You could declare the variable in a scope that includes the 2 functions:

{ my $myvar

  sub foo{
    $myvar = "Hello";
  } 

  sub foo1{
    my $myvar1 = $myvar;   
  }
}

That is not really elegant though, and can be hard to maintain, as it is not clear in foo1 where the value of $myvar was set. It is probably better to pass the variable as an argument.

sub foo {
    my $myvar = "Hello";
    return $myvar;
}

sub foo1 {
  my( $myvar)= @_;
  my $myvar1 = $myvar;
}

# calling code
my $myvar= foo();
foo1( $myvar);

Note that all 3 $myvar are different variables, in different scopes.

As a side note, using prototypes (sub foo()) is probably not a good idea, unless you really know what they are doing, which is likely not to be the case ( see The problem with prototypes for a discussion on prototypes)

这篇关于全局变量,Perl中的子程序变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆