LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   simple Perl Question (https://www.linuxquestions.org/questions/programming-9/simple-perl-question-250746/)

whohasit 11-03-2004 03:40 PM

simple Perl Question
 
This issue is driving me crazy since I declared 2 old variables as 'my'.

Everything worked under dynamic assignment (and using 'our').

Here is a more basic example.... can you tell me why test2 (using 'my') does not print "hello"?


#!/usr/local/bin/perl

&test1();
&test2();

sub test1 {
our($x,$y)=(); # using 'our'
$x='hello';
$y='x';
print "$$y\n"; # prints hello
}

sub test2 {
my($a,$b)=(); # using 'my'
$a='hello';
$b='a';
print "$$b\n"; # prints nothing!!
}


Thanks in advance for your sanity.


-w

secesh 11-03-2004 04:29 PM

i like perl... i've played with references before, but never quite like this...

here's what i came up with; the best i can think is it's a scope issue, but i can't explain it...

Code:

#!/usr/bin/perl

#use strict;

&test1;
&test2;
&test3;

sub test1 {
    our($x,$y)=('hello',\$x);
    print "$$y\n";
    ##WORKS
}
sub test2 {
    my($a,$b)=('hello',\$a);
    print "$$b\n";
    ##NOTHING
}
sub test3 {
    my $a = 'hello';
    my $b = \$a;
    print "$$b\n";
    ##WORKS
}


whohasit 11-05-2004 08:44 AM

Resolved.

Thanks for your comments and effort.

Explained:

This *is* a scoping issue.

The symbolic references (variable representing a variable) is usually a bad idea and will be detected/errored using strict refs pragma. Symbolic references look to global (package) scope but our declarations and work above has happend with 'my', or lexical scope. Hence, these worked fine when 'my' was not used. --- In summary, hard references ($a_ref = \$a) better "mean what they say" while symbolic references (as I've heard) can better do damage from a far.

Anyway, Hashes should meet/replace this particular requirement.

secesh 11-05-2004 10:52 AM

thanx for all that, i'm sure i'll review it to learn that myself later.

glad you got it fixed.


All times are GMT -5. The time now is 01:22 PM.