perl - Context and the Comma Operator -
one of colleagues used comma after statement instead of semi-colon, resulted similar below code:
my $special_field = 'd'; %field_map = ( 1 => 'a', 2 => 'b', 3 => 'c', ); sub _translate_to_engine { ($href) = @_; %mapped_hash = map { $field_map{$_} => $href->{$_} } keys %$href; $mapped_hash{$special_field} = fakeobject->new( params => $mapped_hash{$special_field} ), # << comma here return \%mapped_hash; }
at first surprised passed perl -c
, remembered comma operator
, thought understood going on, results of 2 print statements below made me doubt again.
my $scalar_return = _translate_to_engine( { 1 => 'uno', 2 => 'dos', 3 => 'tres' } ); print dumper $scalar_return; # {'c' => 'tres','a' => 'uno','b' => 'dos','d' => bless( {}, 'fakeobject' )}
this call made in scalar context , result expected result. comma operator evaluated lhs of comma discarded, evaluated rhs. don't believe can return value of rhs here, because evaluating return statements leaves subroutine.
my @list_return = _translate_to_engine( { 1 => 'uno', 2 => 'dos', 3 => 'tres' } ); print dumper \@list_return; # [{'c' => 'tres','a' => 'uno','b' => 'dos','d' => bless( {}, 'fakeobject' )}]
this call made in list context result same call in scalar context. what think happening here: both arguments evaluated since sub called in list context, when rhs evaluated return statement executed lhs discarded.
any clarification on specific semantics happen in either case appreciated.
your explanation accurate.
the context in _translate_to_engine
called affects context in final expressions of function evaluated, including argument return
. there 2 expressions affected in case: comma mentioned, , \%mapped_hash
.
in first test, returned value \%mapped_hash
evaluated in scalar context. , in second, returned value \%mapped_hash
evaluated in list context. \%mapped_hash
evaluates reference hash, regardless of context. such, result of sub same regardless of context.
Comments
Post a Comment