in reply to Using eval to create a hash

The statements
    my %index2;
    eval{ %index2 = ( $index ) };
are equivalent to the statement
    my %index2 = ( $index );
with the only difference being the time at which they are evaluated: the eval statement is evaluated at run time; the other statement is evaluated at compile time | the eval statement is executed such that run-time errors are captured; both statements must be syntactically correct at compile time. (Thanks to Anonymonk for pointing out below the original confusion of this statement. As always, see The Docs for full details!)

But consider
    my %index2 = ( $index );
This statement attempts to initialize a hash with the single string  $index used as a key (and with no associated value) and not with a key/value pair. That's not going to work. Instead, consider

c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le "my $index = q{1 => 'foo', 2 => 'bar', 3 => 'baz'}; my %hash = ( $index => 'foobar' ); print Dumper \%hash; " $VAR1 = { '1 => \'foo\', 2 => \'bar\', 3 => \'baz\'' => 'foobar' };
Here, it's possible to see that the entire string of  $index becomes the key for the value 'foobar'.

Doing a full string eval would have given you the result you expected:

c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le "my $index = q{1 => 'foo', 2 => 'bar', 3 => 'baz'}; my %hash; eval qq{ %hash = ($index); }; print Dumper \%hash; " $VAR1 = { '1' => 'foo', '3' => 'baz', '2' => 'bar' };
or maybe just
c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le "my $index = q{1 => 'foo', 2 => 'bar', 3 => 'baz'}; my %hash = eval qq{ ($index) }; print Dumper \%hash; " $VAR1 = { '1' => 'foo', '3' => 'baz', '2' => 'bar' };
Update: Or indeed just  my %hash = eval $index; as LanX points out below!

See eval for a discussion of the differences between the
    eval { statement; ...; };
and
    eval "statement; ...;";
forms (referred to respectively as  eval BLOCK and  eval EXPR in the doc).


Give a man a fish:  <%-(-(-(-<

Replies are listed 'Best First'.
Re^2: Using eval to create a hash
by Anonymous Monk on Jun 01, 2015 at 10:14 UTC
    the eval statement is evaluated at run time; the other statement is evaluated at compile time.

    I don't think that's accurate for the eval BLOCK form... perhaps you're thinking of evaling a string? Also it depends on what you mean by "evaluated" (compiled vs. executed).