in reply to Re: PUSH Question
in thread PUSH Question

Im sorry,I should have said that the whole infix operator thing is very confusing. I really need basic help on this one. I dont know what gets stored in what. whats and array and whats a hash in this statement:
push @{ $config->{groups}->{$last_group}
I do understand the basic push and everything I see in the manual. Unfortunately, I cant find this type of syntax in the manual.

Replies are listed 'Best First'.
Re^3: PUSH Question
by FunkyMonk (Bishop) on Aug 16, 2008 at 15:58 UTC
    From the beginning...

    $config is a hashref. It can be dereferenced to get the hash itself by prefixing it with %: %$config. Except there'll be precedence issues, so %{$config} is better. The values in the hash can be accessed via their keys like so ${$config}{groups}. But that's too longwinded. The "pointer" operator -> is used to shorten %{$config}{groups} to $config->{groups}.

    The value associated with that particular key is another hashref, so that is accessed with another use of -> shortcut: $config->{groups}->{$last_group}.

    That yields an arrayref that can also be shortcutted with the "pointer" operator to access individual elements, or using @{ ... } to access the dereferenced array, which is what you need for a push.

    Hence (with typo's fixed):

    push @{ $config->{groups}->{$last_group} }, $line;

    Perhaps a little commented Perl will make easier to understand:

    use Data::Dumper; my $last_group = "group_z"; my $line = "a line"; my $config = { # a hash... groups => { # ...of a hash... group_z => [ # ...of a list 2, 3, "Peter", "Pan", ], }, }; push @{ $config->{groups}->{$last_group} }, $line; print Dumper $config;

    Outputs:

    $VAR1 = { 'groups' => { 'group_z' => [ 2, 3, 'Peter', 'Pan', 'a line' ] } };

    Have a look at perlref and perlreftut if you don't properly understand references yet, and then go on to read perldsc.

    Update: Fixed a typo. Thanks ysth.


    Unless I state otherwise, all my code runs with strict and warnings