Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does the scope of array reference matter in this sample code

Tags:

perl

#!/usr/bin/perl

    A();
    B();

    sub A {
        my @array = qw(value_1 value_2);
        $array_ref = \@array;
    }

    sub B {
        foreach my $i ( @{$array_ref} ) {
            print "Array Value: $i \n";
        }
    }

Since the array is declared using the 'my' keyword, could the array reference be lost ? Can any one brief me over this.

like image 796
Anil Avatar asked Sep 20 '26 00:09

Anil


1 Answers

No, the scope of the variable expires, but not the memory address. The data will remain.

Isn't this something you could have simply tried? =) I just copy/pasted your code and tried it, and it worked fine.

For proper encapsulation, though, you really should return the array ref instead:

B(A());
# Or
my $aref = A();
B($aref);

sub A {
        my @array = qw(value_1 value_2);
        return \@array;
}

sub B {
    my $array_ref = shift;
    foreach my $i ( @$array_ref ) {
        print "Array Value: $i \n";
    }
}
like image 126
TLP Avatar answered Sep 21 '26 16:09

TLP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!