Remy Guo wrote:
hi all,
I've got a problem in following script:
sub A  {
    our %a;
    $a{"fred"} = 1;
    $a{"bella"} = 2;
...
}
sub B {
    if ($fred != $a{"fred"})  {
        print "fred failed.\n";
    }
    if ($bella != $a{"bella"}  {
        print "bella failed.\n";
    }
}

The problem is, I made the hash %a in sub A but in sub B, the value in hash
%a is never read. The declaration "our" seems not effect.
Why?...


If fred is spending this much time with bella,
don't let wilma find out.

Consider this:

#!./perl

use warnings;
use strict;

A();
B();

BEGIN {
my %a;
my $fred = 0;
my $bella = 2;
sub A  {
    $a{"fred"} = 1;
    $a{"bella"} = 2;
}
sub B {
    if ($fred != $a{"fred"})  {
        print "fred failed.\n";
    }
    if ($bella != $a{"bella"}) {
        print "bella failed.\n";
    }
}}

I'm demonstrating that you can enclose multiple
subroutines in one block, and share variables
between them.  Your question was about %a, and
that is addressed.  You never mentioned where
$fred and $bella are given their values, so I
included them, too.  But in order to call A()
and B() before their blocks are defined, I had
to make the enclosing block a BEGIN block.

This is getting beyond the beginner stage, and
it's rare that you would do something like this,
but I think it's instructive to know, given your
question.

After you read all the docs about references :-),
read this about scoping:

http://perl.plover.com/FAQs/Namespaces.html

including note number 3.

Cheers,

Brad

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to