On Mon, Apr 3, 2017 at 6:55 PM SSC_perl <p...@surfshopcart.com> wrote:

>         Reading http://perldoc.perl.org/perlreftut.html I see it’s
> possible to create a scalar reference.  What situation would require
> someone to create a reference to a scalar?  I thought refs were only useful
> for passing complex data structures.  Is it just because Perl lets you, or
> is there a reason I’m not aware of?  It seems like it would just be
> redundant.


It is mostly used to avoid copying large amounts of data.  If you are using
Perl 5.20.0 or newer, this is not necessary as long as you aren't changing
the data as strings are now COW (copy-on-write).  Prior to Perl 5.20.0 if
you had code like:

my $big = "a" x (1024*1024*1024); # a gigabyte of 'a's

sub foo (
    my $arg = shift;
);

foo($big)

then it had to copy the whole gigabyte into a new string.  If this was
something you expected, you could (and probably still should if you need to
modify the string) say

sub foo (
    my $ref = shift;

    # do stuff with $$ref
);

and that would not create a copy.

Other uses include

* flyweight/inside-out objects:
http://www.perl.com/pub/2003/06/13/design1.html#flyweight
* Signaling/metadata (eg the open function will open an in-memory file if
passed a scalar ref of the file's contents)
* in/out function parameters without having to use the clunky $_[index]
aliasing (not recommended, really only useful in languages that don't have
multiple return values)
* storing the same scalar in more than data structure (warning this can
lead to spooky-action-at-a-distance bugs)

Reply via email to