Usecase reference to scalar in perl?

I am studying perl references, I understand the usefulness of references to hases or arrays. But think about in which scenarios a reference to a scalar value may be useful.

my $x = 1;
my $sr = \$x;

where is it useful to use $$srinstead of direct use $x?

For example, when traversing any deep structure, hashref is not a common practice to return a link if the given node is hashref or arrayref but returns a scalar value directly instead of returning a reference to a scalar?

Are there several functions or modules that use or return references to scalars instead of returning a scalar value?

+4
source share
5 answers

, , .

.

sub increment_this {
     my ( $inc_ref ) = @_;
     ${$inc_ref}++;
}  

, , , , , chomp, $_.

, - $_ . :

my @array = qw ( 1 2 3 );
foreach ( @array ) {
    $_++;
}

print @array; 

$_ .

+3

, : , , , , . perreal , : .

, , , , perreal Sobrique. :

use strict;
use warnings;
use Data::Dumper;

my $string;
open my $fh, ">", \$string or die $!;
print $fh "Inside the string";

print Dumper $string;
# prints $VAR1 = 'Inside the string';
+3

:

my $v = 1;
my %h1 = (a=>\$v);
my %h2 = (b=>\$v);   
$v++;
print ${$h1{a}}, "\n";
print ${$h2{b}}, "\n";

:

2
2
+2

, :

sub my_sub {
    my $str = shift;  #makes a copy of a reference => cheaper
    #do something with $$str
}

#...
$x = ' ... large string ...';
my_sub(\$x);
+1

@TLP , :

File transfer. A good practice for file manipulation is to use lexical files to avoid pollution of the namespace.

sub write_header {
  my ( $fh_ref ) = @_;
  print ${$fh_ref} "This is a header\n"; 
}

open ( my $output, ">", "output_filename" );
write_header ( \$output );
write_content ( \$output );
write_footer ( \$output );
close ( $output );
0
source

All Articles