[Pdx-pm] Different data structures for Hash of array, same code (mostly)

Hans Dieter Pearcey hdp.perl.pm.pdx at weftsoar.net
Wed Nov 18 09:11:27 PST 2009

Excerpts from Daniel Herrington's message of Wed Nov 18 10:12:07 -0500 2009:
>        my @arJobNamesB = $ref_arJobNamesB;

I bet you meant '@$ref_arJobNamesB'.

Your code would probably be easier to skim for this kind of thing if it were
less verbose.  For example:

>            if ($newBoxNameH{$newBoxName}) {
>                my $ref_arJobNames = $newBoxNameH{$newBoxName};
>                my @arJobNames = @$ref_arJobNames;
>                push (@arJobNames,$newJobName);
>                $newBoxNameH{$newBoxName} = \@arJobNames;
>            } else {
>                my @arJobNames;
>                push (@arJobNames,$newJobName);
>                $newBoxNameH{$newBoxName} = \@arJobNames;
>            }

  my @foo;
  push @foo, $x;
  $thing = \@foo;

can be much more easily written as

  $thing = [ $x ];

In fact, the whole conditional I quoted above could be one line.

  push @{ $newBoxNameH{$newBoxName} }, $newJobName;

Perl will automatically turn the nonexistent hash element into an array
reference for you.  If this is too magical for your taste, default it to an
empty arrayref first:

  $newBoxNameH{$newBoxName} ||= [];


More information about the Pdx-pm-list mailing list