in reply to PUSH Question

You can only ever push onto an array.

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

could have been written as

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

if that helps.

Some reference material:
perlref
perllol
References Quick Reference
Dereferencing Syntax

Update: Oops, those two snippets aren't the same due to autovivification.

my $ref_to_array = $config->{groups}->{$last_group} push @$ref_to_array, $line; # In case $ref_to_array was autovivified, $config->{groups}->{$last_group} = $ref_to_array;

Or vivify it explicity,

my $ref_to_array = $config->{groups}->{$last_group} ||= []; push @$ref_to_array, $line;

That kind of confuses the point, which was that the expression within the curlies returns an array reference, which is derefenced by @{}, resulting an array being passed to push.

Replies are listed 'Best First'.
Re^2: PUSH Question
by emusic32 (Initiate) on Aug 16, 2008 at 14:40 UTC
    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.
      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