perl - Dereferencing a scalar reference in a hashref -
i have hashref arrayrefs , scalarrefs values. can access values of arrayrefs, not scalar refs.
foreach (keys %$data) { if (ref $data->{$_} eq 'array') { push @values, $data->{$_}[0]; } elsif (ref $data->{$_} eq 'scalar') { push @values, $data->??? } }
how do that?
to dereference scalar reference, preface value scalar sigil, $
:
if (ref $data->{$_} eq 'scalar') { push @values, ${$data->{$_}}; }
your arrayref case isn't quite right, dereferencing first arrayref element, rather getting elements of array. however, since storing scalar, can't store arrayref's values, unless transformed them scalar in fashion -- say, getting number of elements in arrayref (which when evaluate array in scalar context), or concatenating array elements string.
see perldoc perlref:
using references
- anywhere you'd put identifier (or chain of identifiers) part of variable or subroutine name, can replace identifier simple scalar variable containing reference of correct type:
$bar = $$scalarref; push(@$arrayref, $filename); $$arrayref[0] = "january"; $$hashref{"key"} = "value"; &$coderef(1,2,3); print $globref "output\n";
it's important understand not dereferencing $arrayref[0] or $hashref{"key"} there. dereference of scalar variable happens before key lookups. more complicated simple scalar variable must use methods 2 or 3 [below]. however, "simple scalar" includes identifier uses method 1 recursively. therefore, following prints "howdy".
$refrefref = \\\"howdy"; print $$$$refrefref;
Comments
Post a Comment