http://www.perlmonks.org?node_id=1038262


in reply to Getting rid of a temporary variable in AoH

Once the @fields array is declared inside the loop, you can safely destroy it:
while ( my $line = <DATA> ) { chomp $line; my @fields = qw( login uid gid name home + shell ); my @items = $line =~ /^([\-\w]+):x:(\d+):(\d+):([\-\w\s\(\)\,]*):([\w\/]+) +:([\w\/]+)$/ or die "Malformed input [$line]"; push @users, {}; $users[-1]{ shift @fields } = shift @items while @fields; }
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Getting rid of a temporary variable in AoH
by AnomalousMonk (Archbishop) on Jun 12, 2013 at 02:58 UTC

    A variation (imagine the  my $datum = shift @data is reading a file; no need to create  @fields array each time through loop; state only available with 5.10+; either version works the same):

    >perl -wMstrict -MData::Dump -lE "my @data = ( 'foo 123 %^&', 'huggle 9876 @*', 'ab 55555 !@$%^&', ); ;; my @users; while (my $datum = shift @data) { # use constant FIELDS => qw( alphas digits stuff) +; state $fields = [ qw( alphas digits stuff) ] +; my @items = $datum =~ m{ ([[:alpha:]]+) \s+ (\d+) \s+ ([^[:alpha:]\ +d]+) }xms; # @{ $users[@users] }{ FIELDS() } = @items; @{ $users[@users] }{ @$fields } = @items; } ;; dd \@users; " [ { alphas => "foo", digits => 123, stuff => "%^&" }, { alphas => "huggle", digits => 9876, stuff => "\@*" }, { alphas => "ab", digits => 55555, stuff => "!\@\$%^&" }, ]