Global variable, subroutine variable Question in Perl

How to pass the value of a subroutine variable to another subroutine variable, Can I use a global variable.

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

I tried using a batch and global variable, but could not.

 Package Bar; our $bar; 

Thanks.

+4
source share
5 answers

You can declare a variable in a scope that includes 2 functions:

 { my $myvar sub foo{ $myvar = "Hello"; } sub foo1{ my $myvar1 = $myvar; } } 

This is not very elegant, but it can be difficult to maintain since in foo1 where $myvar was set. It is probably best 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 $myvar 3 $myvar are different variables in different areas.

As a side note, using prototypes ( sub foo() ) is probably not a good idea unless you really know what they are doing, which is probably not the case (see Prototyping Problem for a discussion of prototypes)

+13
source

How to pass the value of a subroutine variable to another subroutine variable, can I use global variables?

Yes, you can:

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

This works even with "use strict"; and "use warnings."

I tried using a batch and global variable, but could not.

Package variables for variables that you want to export outside of your package, and not for variables that you want to split between two routines in the same package.

+5
source

Just don't use my :

 #!/usr/bin/perl sub foo() { $myvar = "Hello\n"; } sub foo1() { $myvar1 = $myvar; print $myvar1; } print "here we go!\n"; foo(); foo1(); 

However, I do not recommend this programming method.

+4
source

You have several approaches.

The easiest way is not to declare a variable with my . But this requires the use strict; and not recommended as a result.

You can declare a variable outside functions at the top of your script. This variable will be available for all functions below. This is a consequence of scope : variables declared outside a set of curly braces are usually available inside any subsequent curly braces.

You can declare your variable using the pragma use vars qw/$myvar/; . This essentially makes your variable available in all of the following code.

+2
source

The following code can demonstrate a solution to what you are describing:

 #!/usr/bin/perl use strict; my $var = "hello"; sub foo { local *var; print "$var world\n"; $var = "hi"; } sub bar { local *var; print "$var world\n"; $var = "hey"; } foo(); bar(); print "$var world\n"; 

The result should be:

 hello world hi world hey world 
0
source

Source: https://habr.com/ru/post/1311835/


All Articles