How does this example of passing arrays by reference work in Perl? -
i looking on post on how pass arrays (or lists) scalars when stumbled upon s.o. post... passing value - s.o.
i found chosen answer solution worked, since trying learn perl know how worked. in line
my($inval, $invaltwo, $inarray, $inarraytwo) = @_; i see author placing input parameters passed sub program scalar variables. then, in line
@{$inarray} he said "use reference arrays". did mean , going on in second line? have not seen operators combined that.
the first thing keep in mind arrays , lists not same.
a reference scalar holds memory address of else - array, hash, scalar, etc. it's fancy kind of pointer.
subroutines in perl take list of arguments (and return list of results.) common stumbling block when want like
mysub( @foo, @bar ) and realize elements of @foo , @bar got flattened single list in subroutine. if know size of @foo ahead of time can grab right number of elements off beginning of list, don't.
references can solve problem, since scalars. if pass references @foo , @bar, know subroutine have 2 parameters deal with, regardless of sizes of referant arrays.
but still need @ data in arrays. that, have tell perl go thing references pointing to. called dereferencing.
in perl, there 2 common ways dereference array reference:
- to whole array, use
my @array = @$ref; - to element in array, use
my $elem = $ref->[42].
note first example written @{ $ref }, curlies not required unless need disambiguate nested structure. people prefer use curlies find add clutter , unnecessary.
for more on exciting topic of references, check out
Comments
Post a Comment