I'm learning perl references, I understand the usefullness of the references to hases or arrays. But thinking about in what scenarios can be useful a reference to an scalar value.
my $x = 1;
my $sr = \$x;
where can be useful to use $$sr
, instead of direct use of $x
?
For example, when traversing any deep hashref structure, isn't the common practice returning a reference if the given node is hashref or arrayref, but returning directly the scalar value instead of returning a reference to the scalar?
Exists some functions or modules what uses or return references to scalars, instead of returning the scalar's value?
In a subroutine, when you want to directly modify the values being passed into it.
e.g.
sub increment_this {
my ( $inc_ref ) = @_;
${$inc_ref}++;
}
Bit of a trivial case I know, but perhaps more pertinent would be examples like chomp
which removes trailing letters from a variable or $_
.
If you think about it though - $_
is often effectively a reference.
If you do this:
my @array = qw ( 1 2 3 );
foreach ( @array ) {
$_++;
}
print @array;
Modifying $_
has modified the contents of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With