Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Pointers and References

by GrandFather (Saint)
on Nov 23, 2020 at 04:20 UTC ( #11124048=note: print w/replies, xml ) Need Help??


in reply to Pointers and References

Perl doesn't have "pointers". Sure, under the hood they are everywhere, but it's not useful to think about pointers in Perl. The reason we talk about references is that there is some extraordinarily useful under the hood baggage associated with references. Perl uses reference counted memory management. A reference to something else is one type of data that a scalar variable can contain. You can have references to pretty much anything and you can use ref to tell you what you have a reference to. That sums up to, you hardly ever need to think about memory management in Perl and most things "just work".

So, in answer to question 1: no, it contains a reference (which might be an address of something, but you don't {and shouldn't} need to know what).

$ in Perl as a sigil means "give me a scalar value". In answer to 2: $$ means give me the scalar referred to by the scalar xxx. Because you can assign values to a scalar when you use $$ in an assignment you are assigning to the scalar referred to by the scalar. No pointers to be seen here.

A more useful example is:

use warnings; use strict; use v5.10; do { my $variable = 22; my $refVar = \$variable; $$refVar = 25; say "Look at that! \$variable now equals $variable"; my $two = 2; my ($sum, $diff) = sum_and_diff(5, $two); say "the sum of 5 and $two is $sum"; say "and the difference is $diff"; }; sub sum_and_diff { my ($lhs, $rhs) = @_; return $lhs + $rhs, $lhs - $rhs; }

Prints:

Look at that! $variable now equals 25 the sum of 5 and 2 is 7 and the difference is 3

Useful because it is a reminder that Perl doesn't need "output parameters" because it can return multiple values from a sub. References in Perl are most useful in building interesting structures which are a mixture of arrays, hashes and scalar values.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Replies are listed 'Best First'.
Re^2: Pointers and References
by bliako (Prior) on Nov 23, 2020 at 13:10 UTC
    Useful because it is a reminder that Perl doesn't need "output parameters" because it can return multiple values from a sub.

    Correct. OTOH "output parameters" are also needed and very useful, for example when an existing huge array must be modified from within a sub.

      I don't really think of mutable arguments like that as "output parameters". "I/O parameters" maybe. I the sense that C like languages use output parameters where the sole job of the parameter is to return information from the function I don't see a need for output parameters in Perl, although passing references in the parameter list could be used that way.

      The run time and memory cost of returning a reference to a large structure, or a list of references to large structures has essentially the same overhead on Perl as passing references back as parameters. Since returning a list of stuff is natural in Perl returning a list of references makes for easier to understand code than working with output parameters.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

        I have to say I come from C and back then (yes! Then) without goofle and the free literature it was a lot of hard work to conquer the pointers. I can't let it go now. I have often debated internally whether thinking in C while writing Perl was a good habit/idea/practice. It is NOT. But when %$^$& comes to shovel I have to think of some ways to make it faster. Because I am too lazy to program it in C eventually. And these are some of the tricks I pull.

        That's why my subs most of the times have a hashref of params as input (as opposed to array-style (file => 'aaa' , action => 'delete')) and I always return a hashref or arrayref or object back, but never ever an array. I think somewhere an angel dies when I do that. Cargo-culting perhaps, plus I am not a natural Perl-er.

        bw, bliako

Re^2: Pointers and References
by Leudwinus (Beadle) on Nov 25, 2020 at 15:13 UTC
    So, in answer to question 1: no, it contains a reference (which might be an address of something, but you don't {and shouldn't} need to know what).

    Got it. Thanks for that clarification!

    $ in Perl as a sigil means "give me a scalar value". In answer to 2: $$ means give me the scalar referred to by the scalar xxx. Because you can assign values to a scalar when you use $$ in an assignment you are assigning to the scalar referred to by the scalar. No pointers to be seen here.

    Ok, I think I understand what you are saying. Taking your explanation one step further, I was wondering if I could use a "triple dollar sign" ($$$). Not that this would be idiomatic or anything but apparently you can:

    my $variable = 22; my $pointer = \$variable; say "The address of \$variable, which contains the value $variable,"; say "is $pointer"; $$pointer = 25; say "Look at that! \$variable now equals $variable"; my $double_pointer = \$pointer; $$$double_pointer = 50; say "Look at that! \$variable now equals $variable";
    which results in
    The address of $variable, which contains the value 22, is SCALAR(0x801e64540) Look at that! $variable now equals 25 $double_pointer = REF(0x801e644b0) Look at that! $variable now equals 50
    ...Perl doesn't need "output parameters" because it can return multiple values from a sub.

    I didn't know that! That is very cool!

    References in Perl are most useful in building interesting structures which are a mixture of arrays, hashes and scalar values.

    I guess I just need to keep re-reading the excellent documentation and trying this out. I implicitly understand the power of references but still struggling with applying them.

      Please, in the context of Perl at least, expunge "pointer" from your head. Perl references are simply not pointers. Yes, there are pointers under the hood, but thinking of them as pointers will just make your brain hurt more.

      Yes, you can nest scalar references, but it is extraordinarily unusual to do so. Again, don't think about pointers. In other languages it can be useful to use multiple levels of indirection. In Perl you can end up with convoluted data structures containing a wild mix of references to nested data of different types, but that seldom turns into nested references to a simple scalar.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
Re^2: Pointers and References
by Bod (Chaplain) on Nov 23, 2020 at 18:22 UTC

    Really helpful explanation GrandFather

    In your example code, what is achieved by wrapping part of the code in a do block?
    Is this purely to aid legibility or does it have a functional impact? The documentaion doesn't answer this query.

      Anonymous Monk is quite right. The do block is there to wrap up a "main". I don't usually bother, but in this case a previous iteration of the sub had variables with the same name as were in the main block of code so I used the do block to limit the scope of those variables.

      As a general thing avoiding global variables is good. In larger scripts I write a formal sub main to ensure the only global variables are deliberate and explicit. So the do block is a light weight version of that practice that remained somewhat beyond its use by date, but a useful discussion point as it turns out.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
        > I used the do block to limit the scope of those variables.

        maybe consider a "naked BLOCK" instead of do BLOCK to limit the scope.

        { my $limited_in_scope; }

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery

        Where I want to explicitly show that a variable is deliberately global, I declare it with our.

      In this case, only the latter. He is doing it as a personal practice for designating the "main routine" of his program.

      do does have definite functional uses. None of them are being leveraged here.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11124048]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2021-06-17 00:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (82 votes). Check out past polls.

    Notices?