Global Variable, subroutine variable Question in Perl

Nano HE picture Nano HE · Jun 4, 2010 · Viewed 31.6k times · Source

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.

Answer

mirod picture mirod · Jun 4, 2010

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)