0

I can initialize a hash from a list, e.g:

my %hash = (1..10);
my %hash2 = split /[\n=]/;

Is there a better (briefer) way to add lists of new key/values to a hash than using temporary variables?

while (<>) {
    my ($k, $v) = split /=/, $_, 2;
    $hash{$k} = $v;
}
RobEarl
  • 7,862
  • 6
  • 35
  • 50

2 Answers2

1

It's possible, yes. It's rather like adding some numbers to an existing total - you might accomplish that like this:

my $total = 1 + 2 + 3;   # here's the existing total

# let's add some additional numbers
$total = $total + 4 + 5;   # the $total variable appears both
                           # left and right of the equals sign

You can do similar when inserting values to an existing hash...

my %hash = (a => 1, b => 2);  # here's the existing hash.

# let's add some additional values
$_ = "c=3" . "\n" . "d=4";
%hash = (%hash, split /[\n=]/);  # the %hash variable appears both
                                 # left and right of the equals sign

With addition, there's a nice shortcut for this:

 $total += 4 + 5;

With inserting values to a hash, there's no such shortcut.

tobyink
  • 13,478
  • 1
  • 23
  • 35
0

Maybe I'm wrong but the next

use 5.014;
use warnings;
use Data::Dumper;

#create a hash
my %hash = map { "oldvar" . $_ => "oldval" . $_ } (1..3);

#add to the hash
%hash = (%hash, map {split /[=\n]/}  <DATA>);
say Dumper \%hash;

__DATA__
var1=val1
var2=val2
var3=val3

prints

$VAR1 = {
      'oldvar1' => 'oldval1',
      'oldvar2' => 'oldval2',
      'var1' => 'val1',
      'var3' => 'val3',
      'oldvar3' => 'oldval3',
      'var2' => 'val2'
    };
clt60
  • 62,119
  • 17
  • 107
  • 194