Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usecase of an reference to scalar in perl?

Tags:

perl

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?

like image 358
kobame Avatar asked Jan 09 '23 20:01

kobame


1 Answers

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.

like image 186
Sobrique Avatar answered Jan 22 '23 10:01

Sobrique