You can avoid modifying $_ within the sub, by doing the initialization of $hash_ref in a BEGIN block:
As a small bonus, the sub doesn't need to perform a test that would have been true only once.{ my $hash_ref; BEGIN { while (<DATA>){ chomp; my ($str, $num) = split /\|/; $hash_ref->{$str} = $num; } } sub get_number{ my ($num) = @_; return $hash_ref->{$num}; } }
Update: In light of hv's comments below, I conclude that, in this case at least, saving the while (<DATA>) is not worth all the fuss and worry over $_. Hence in the revision below, the loop does not use $_.
{ my $hash_ref; BEGIN { while (defined (my $line = <DATA>)){ chomp $line; my ($str, $num) = split /\|/, $line; $hash_ref->{$str} = $num; } } sub get_number{ my ($num) = @_; return $hash_ref->{$num}; } }
the lowliest monk
In reply to Re: Closure producing 'Modification of read-only value' error
by tlm
in thread Closure producing 'Modification of read-only value' error
by wfsp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |