Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

push to a referenced array

by biga (Sexton)
on Sep 27, 2008 at 20:10 UTC ( #714053=snippet: print w/replies, xml ) Need Help??
Description: This useful function performs 'push' into a referenced array. It creates the array if it doesn't exist.
my $a={};
ref_push $a->{ARRAY}, "some", "list";
But the code is a bit obfuscated... %)
sub ref_push{$_[0]?push@{+shift},@_:shift@{$_[0]=[@_]}}
Replies are listed 'Best First'.
Re: push to a referenced array
by moritz (Cardinal) on Sep 27, 2008 at 20:21 UTC
    Is there any advantage over push @{$a->{ARRAY}}, "some", "list";? I for one can't see any...
      Looks like the only benefit of this function is that you can omit surrounding @{}, which makes code cleaner. You may also add a ref check to this function for debug purposes.

        Hiding implentation details by writing tiny functions instead of just using references the way everybody else does rarely makes code cleaner. This is doubly true when the function you replace it with is obfuscated.

        If you really need a golf function to do it though, it can be made shorter...

        sub ref_push{push@{$_[0]||=[]},@_[1..$#_]}
        We're not surrounded, we're in a target-rich environment!
        ... but you have to write a wrapper for every built-in list function.

        To me it feels more like this function would be used by people not confident with references and autovivification, in which case I recommend reading perldata and perlreftut instead of writing wrappers.

Re: push to a referenced array
by biga (Sexton) on Sep 27, 2008 at 20:19 UTC
    And if you want a "normal" variant:
    sub ref_push { if ( !$_[0] ) { $_[0] = [ @_[1..$#_] ]; } else { push @{$_[0]}, @_[1..$#_]; } }

      Not safe enough:

      sub ref_push { if (ref $_[0] eq "ARRAY") { push @{$_[0]}, @_[1..$#_]; } elsif (ref $_[0]) { warn "Cannot push onto non-ARRAY ref"; } elsif (!defined $_[0]) { $_[0] = [ @_[1..$#_] ]; else { warn "Cannot push: Variable already defined as something else" +; } } # ref_push

      Enjoy, Have FUN! H.Merijn
Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://714053]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (1)
As of 2022-05-22 20:43 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (81 votes). Check out past polls.