Why references??

Discussion in 'Perl Misc' started by Thomas Deschepper, Feb 9, 2004.

  1. I've been reading Beginning Per & Programming Perl from O'Reilly for some time
    now and I'm getting used to references and how to grow them..

    But why would someone use a reference if they can use a normal variable? Yeah, I
    know, with references you can grow complex data structures, but in simple
    programs, why would you use them (=references)?

    Thanks for your (smart) answers :)

    Greets from Belgium,

    Thomas
     
    Thomas Deschepper, Feb 9, 2004
    #1
    1. Advertising

  2. In article <c08d6u$89k$>,
    Thomas Deschepper <> wrote:
    :I've been reading Beginning Per & Programming Perl from O'Reilly for some time
    :now and I'm getting used to references and how to grow them..

    :But why would someone use a reference if they can use a normal variable? Yeah, I
    :know, with references you can grow complex data structures, but in simple
    :programs, why would you use them (=references)?

    I've used languages where every subroutine argument was call- by-
    reference, and I've used languages where every subroutine argument
    was call- by- value, and I've used languages where every subroutine
    argument had to be explicitly declared as by-reference or by-value.

    perl, though, implicitly passes a reference if possible, and
    otherwise passes by value. In my opinion, that leads to too much
    chance of making a mistake (and hence to unpredicted behaviour),
    so I prefer to not count on call-by-reference behaviour and instead
    explicitly pass through a reference if I'm expecting to change the
    argument.
    --
    I've been working on a kernel
    All the livelong night.
    I've been working on a kernel
    And it still won't work quite right. -- J. Benson & J. Doll
     
    Walter Roberson, Feb 9, 2004
    #2
    1. Advertising

  3. Thomas Deschepper

    Ben Morrow Guest

    -cnrc.gc.ca (Walter Roberson) wrote:
    > perl, though, implicitly passes a reference if possible, and
    > otherwise passes by value.


    Eh what? Perl always passes aliases into @_, and the standard idiom
    of

    my ($a, $b) = @_;

    then makes copies. What's implicit about that?

    Ben

    --
    Musica Dei donum optimi, trahit homines, trahit deos. |
    Musica truces molit animos, tristesque mentes erigit. |
    Musica vel ipsas arbores et horridas movet feras. |
     
    Ben Morrow, Feb 9, 2004
    #3
  4. Thomas Deschepper

    Guest

    Thomas Deschepper <> wrote:
    > I've been reading Beginning Per & Programming Perl from O'Reilly for some
    > time now and I'm getting used to references and how to grow them..
    >
    > But why would someone use a reference if they can use a normal variable?


    I wouldn't use a reference if I could just as well use a normal variable,
    unless I anticipate the program will eventually evolve such that I
    couldn't use a normal variable there anymore. In that case I would
    preemptively use a reference.

    > Yeah, I know, with references you can grow complex data structures, but
    > in simple programs, why would you use them (=references)?


    I wouldn't. I'm not sure I understand your question. Do you often see
    people gratuitiously using references?

    use strict;
    my $x;
    my $y;
    $$$$y=0;
    while ($$$$x=<>) {
    $$$$y+=$$$$x;
    };
    print $$$$y;


    > Thanks for your (smart) answers :)

    ^
    ass


    Cheers,


    Xho

    --
    -------------------- http://NewsReader.Com/ --------------------
    Usenet Newsgroup Service New Rate! $9.95/Month 50GB
     
    , Feb 9, 2004
    #4
  5. In article <c08eug$ml5$>,
    Ben Morrow <> wrote:

    :-cnrc.gc.ca (Walter Roberson) wrote:
    :> perl, though, implicitly passes a reference if possible, and
    :> otherwise passes by value.

    :Eh what? Perl always passes aliases into @_, and the standard idiom
    :eek:f

    :my ($a, $b) = @_;

    :then makes copies. What's implicit about that?

    It is implicit compared to (say) Pascal's "VAR" notation, or even
    compared to C's (type *) notation. The closest, I guess, would
    be FORTRAN's behaviour.


    I've had a number of practically untracable bugs, with values
    used in one subroutine suddenly reappearing in the next subroutine
    down -- even though the calling routine has the right value for
    the parameter. I eventually decided it was happening mostly in places
    I was using the (shift) idiom, and re-wrote all of those.
    [I -think- I also had it happen a few times where I used my $var = $_[0]
    but I'm not positive about that.] Looking back over the documentation
    of shift, it seems to me that it must be the case that shift preserves
    the property of being an alias, and that for my $var = shift
    that $var ends up an alias to the parameter passed down. That's
    certainly not explicit behaviour.
    --
    "Mathematics? I speak it like a native." -- Spike Milligan
     
    Walter Roberson, Feb 9, 2004
    #5
  6. Thomas Deschepper () wrote:
    : I've been reading Beginning Per & Programming Perl from O'Reilly for some time
    : now and I'm getting used to references and how to grow them..

    : But why would someone use a reference if they can use a normal variable? Yeah, I
    : know, with references you can grow complex data structures, but in simple
    : programs, why would you use them (=references)?

    Style. (?)

    I suspect that someone who uses a lot of references feels comfortable
    with the syntax and may use them even when they are not needed.

    I prefer
    $my_hash{$item}

    but someone else might prefer

    $my_hash->{$item}

    It makes no difference to the interpreter, so use which ever style you
    prefer (they are different of course, it just doesn't _make_ any
    difference).

    If the program has other references (that are needed) that using
    references everywhere might also make the program more consistent,
    stylisticly.

    $myhash1->{$item}
    $myhash2->{$item}
    $myhash3{$item} # huh, why is this different?
     
    Malcolm Dew-Jones, Feb 9, 2004
    #6
  7. Thomas Deschepper

    Ben Morrow Guest

    -cnrc.gc.ca (Walter Roberson) wrote:
    > In article <c08eug$ml5$>,
    > Ben Morrow <> wrote:
    >
    > :-cnrc.gc.ca (Walter Roberson) wrote:
    > :> perl, though, implicitly passes a reference if possible, and
    > :> otherwise passes by value.
    >
    > :Eh what? Perl always passes aliases into @_, and the standard idiom
    > :eek:f
    >
    > :my ($a, $b) = @_;
    >
    > :then makes copies. What's implicit about that?
    >
    > It is implicit compared to (say) Pascal's "VAR" notation, or even
    > compared to C's (type *) notation. The closest, I guess, would
    > be FORTRAN's behaviour.
    >
    > I've had a number of practically untracable bugs, with values
    > used in one subroutine suddenly reappearing in the next subroutine
    > down -- even though the calling routine has the right value for
    > the parameter. I eventually decided it was happening mostly in places
    > I was using the (shift) idiom, and re-wrote all of those.
    > [I -think- I also had it happen a few times where I used my $var = $_[0]
    > but I'm not positive about that.] Looking back over the documentation
    > of shift, it seems to me that it must be the case that shift preserves
    > the property of being an alias, and that for my $var = shift
    > that $var ends up an alias to the parameter passed down. That's
    > certainly not explicit behaviour.


    No, you've got something wrong somewhere, or you're calling subs with
    &.

    perl -le'sub a { my $x = shift; $x++ } my $y = 1; a $y; print $y'
    1

    perl -le'sub a { my $x = $_[0]; $x++ } my $y = 1; a $y; print $y'
    1

    perl -le'sub a { $_[0]++ } my $y = 1; a $y; print $y'
    2

    You only get aliasing if you explicitly manipulate $_[n]. Even so, I
    agree it's rarely useful now we have prototypes. Perl6 will make @_
    contain *readonly* aliases by default, so $_[0]++ will give a run-time
    error.

    Ben

    --
    "If a book is worth reading when you are six, *
    it is worth reading when you are sixty." - C.S.Lewis
     
    Ben Morrow, Feb 9, 2004
    #7
  8. Thomas Deschepper

    Brad Baxter Guest

    On Mon, 9 Feb 2004, Walter Roberson wrote:
    > Looking back over the documentation of shift, it seems to me that it
    > must be the case that shift preserves the property of being an alias,
    > and that for my $var = shift that $var ends up an alias to the parameter
    > passed down. That's certainly not explicit behaviour.


    That's also not what it does. :) It says the opposite in the first line
    of the documentation:

    shift ARRAY
    shift
    Shifts the first value of the array off and returns it, ...

    This is fairly easy to verify:

    sub by_ref { \$_[0] }
    sub by_assign1 { my( $x ) = @_; \$x; }
    sub by_assign2 { my $x = $_[0]; \$x; }
    sub by_shift { my $x = shift; \$x; }

    my $y = 'test';

    print "itself: ",\$y,"\n\n";

    print "by_ref: @{[by_ref ( $y )]}\n";
    print "by_assign1: @{[by_assign1( $y )]}\n";
    print "by_assign2: @{[by_assign2( $y )]}\n";
    print "by_shift: @{[by_shift ( $y )]}\n";

    __END__
    itself: SCALAR(0x106480)

    by_ref: SCALAR(0x106480)
    by_assign1: SCALAR(0x106540)
    by_assign2: SCALAR(0x126f5c)
    by_shift: SCALAR(0x126e90)

    So you can see that with shift, the variable doesn't end up as an alias
    any more than with any of the other assignments. They all copy values--and
    pretty explicitly, it seems to me.

    Regards,

    Brad
     
    Brad Baxter, Feb 9, 2004
    #8
  9. Thomas Deschepper

    Ala Qumsieh Guest

    "Malcolm Dew-Jones" <> wrote in message
    news:...

    > I prefer
    > $my_hash{$item}
    >
    > but someone else might prefer
    >
    > $my_hash->{$item}


    errr .. those two are not the same.

    > It makes no difference to the interpreter, so use which ever style you
    > prefer (they are different of course, it just doesn't _make_ any
    > difference).


    I don't understand how two different things don't make any difference (not
    sure if the sentence itself makes sense, though).

    > If the program has other references (that are needed) that using
    > references everywhere might also make the program more consistent,
    > stylisticly.


    Agreed.

    > $myhash1->{$item}
    > $myhash2->{$item}
    > $myhash3{$item} # huh, why is this different?


    Maybe because $myhash1 and $myhash2 are references to hashes, while $myhash3
    doesn't exist, and %myhash3 is a normal hash?

    --Ala
     
    Ala Qumsieh, Feb 10, 2004
    #9
  10. Thomas Deschepper

    Ben Morrow Guest

    "Ala Qumsieh" <> wrote:
    > "Malcolm Dew-Jones" <> wrote in message
    > news:...
    >
    > > I prefer
    > > $my_hash{$item}
    > >
    > > but someone else might prefer
    > >
    > > $my_hash->{$item}

    >
    > errr .. those two are not the same.


    <snip>

    > > $myhash1->{$item}
    > > $myhash2->{$item}
    > > $myhash3{$item} # huh, why is this different?

    >
    > Maybe because $myhash1 and $myhash2 are references to hashes, while $myhash3
    > doesn't exist, and %myhash3 is a normal hash?


    You're missing the point. If you want to use a hash, you can either
    create it thus

    my %hash = (
    key => $value,
    );

    and use it thus

    $hash{key};

    or you can create it thus

    my $hash = {
    key => $value;
    };

    and use it thus

    $hash->{key};

    .. Which you choose makes no difference to the outcome of the program.

    Ben

    --
    If I were a butterfly I'd live for a day, / I would be free, just blowing away.
    This cruel country has driven me down / Teased me and lied, teased me and lied.
    I've only sad stories to tell to this town: / My dreams have withered and died.
    <=>=<=>=<=>=<=>=<=>=<=>=<=>=<=>=<=>=<=>=<=> (Kate Rusby)
     
    Ben Morrow, Feb 10, 2004
    #10
  11. Thomas Deschepper

    Ala Qumsieh Guest

    "Ben Morrow" <> wrote in message
    news:c098g3$be7$...

    > You're missing the point.


    Hmm .. I think you're right. Thanks.

    > . Which you choose makes no difference to the outcome of the program.


    Then let me throw in my two cents, just to contribute (hopefully)
    constructively to this thread.

    I'm paranoid about the tiny fraction of a millisecond that it takes to
    dereference a reference. So, I tend to avoid references wherever I can. The
    exception comes when passing parameters to/returning values from
    subroutines. Then, I'm more paranoid about the amount of time it takes to
    push/pop values onto the stack.

    And, sometimes references are unavoidable, such as when dealing with
    multi-dim structures and objects. In some situations, using references can
    give more succinct and elegant code. Elegance tends to drive many of my
    coding choices. Alas, it's in the eye of the beholder, so your standards
    might vary.

    Bottom line to OP: do whatever feels more natural to you.

    --Ala
     
    Ala Qumsieh, Feb 10, 2004
    #11
  12. Thomas Deschepper wrote:
    > But why would someone use a reference if they can use a normal
    > variable? Yeah, I know, with references you can grow complex data
    > structures, but in simple programs, why would you use them
    > (=references)?


    - because even simple programs have data structures, which are more complex
    than scalars and one-dimensional arrays or hashes would allow
    - because you want to pass parameters as call-by-reference

    jue
     
    Jürgen Exner, Feb 10, 2004
    #12
  13. Thomas Deschepper wrote:

    > I've been reading Beginning Per & Programming Perl from O'Reilly for some time
    > now and I'm getting used to references and how to grow them..
    >
    > But why would someone use a reference if they can use a normal variable? Yeah, I
    > know, with references you can grow complex data structures, but in simple
    > programs, why would you use them (=references)?
    >
    > Thanks for your (smart) answers :)
    >
    > Greets from Belgium,
    >
    > Thomas


    Apart from the pass-by-reference thing, I usually use:

    my $var = {};

    over:

    my %var = ();

    because to me a reference is a single thing, and an array/hash is a
    group of things. The logic just works better in my head if I'm thinking
    in terms of individual units, even if those units can then be broken
    down later.

    Of course there are stylistic and comprehension up-and-down sides.

    Its purely a personal thinking thing. Unless you're using nested data
    (N-ary arrays, hashes of arrays, etc) there really is very little
    difference between the two.

    MB
     
    Matthew Braid, Feb 10, 2004
    #13
  14. [Monday 09 February 2004 17:41]Thomas Deschepper
    () wrote:

    > I've been reading Beginning Per & Programming Perl from O'Reilly for some time
    > now and I'm getting used to references and how to grow them..
    >
    > But why would someone use a reference if they can use a normal variable? Yeah,
    > I know, with references you can grow complex data structures, but in simple
    > programs, why would you use them (=references)?
    >
    > Thanks for your (smart) answers :)
    >
    > Greets from Belgium,
    >
    > Thomas


    Thanks for the constructive comment on this question guys :) Good newsgroup,
    good programming language ;)
     
    Thomas Deschepper, Feb 10, 2004
    #14
  15. Thomas Deschepper

    Tore Aursand Guest

    On Mon, 09 Feb 2004 17:41:02 +0100, Thomas Deschepper wrote:
    > But why would someone use a reference if they can use a normal variable?


    I've read a lot of the other answers in this group, but none of them seem
    to relate to why I prefer references: performance.

    Copying the reference to a huge array is always faster than copying the
    array itself. It also uses less memory. And - I think references are
    easier to "read" (syntax wise) than "ordinary variables".


    --
    Tore Aursand <>
    "What we see depends mainly on what we look for." -- Sir John Lubbock
     
    Tore Aursand, Feb 10, 2004
    #15
  16. Thomas Deschepper

    Ben Morrow Guest

    Tore Aursand <> wrote:
    > On Mon, 09 Feb 2004 17:41:02 +0100, Thomas Deschepper wrote:
    > > But why would someone use a reference if they can use a normal variable?

    >
    > I've read a lot of the other answers in this group, but none of them seem
    > to relate to why I prefer references: performance.
    >
    > Copying the reference to a huge array is always faster than copying the
    > array itself. It also uses less memory.


    But the semantics are different. If one is correct, the other is
    wrong.

    Ben

    --
    "If a book is worth reading when you are six, *
    it is worth reading when you are sixty." - C.S.Lewis
     
    Ben Morrow, Feb 10, 2004
    #16
  17. "Tore Aursand" <> wrote in message
    news:p...
    > On Mon, 09 Feb 2004 17:41:02 +0100, Thomas Deschepper wrote:
    > > But why would someone use a reference if they can use a normal variable?

    >
    > I've read a lot of the other answers in this group, but none of them seem
    > to relate to why I prefer references: performance.
    >
    > Copying the reference to a huge array is always faster than copying the
    > array itself. It also uses less memory.


    True. But the effect is totally different. You can't replace one with the
    other.

    > And - I think references are
    > easier to "read" (syntax wise) than "ordinary variables".


    That on the other hand is probably a rather unique opinion ;-)

    jue
     
    Jürgen Exner, Feb 10, 2004
    #17
  18. Thomas Deschepper

    Tore Aursand Guest

    On Tue, 10 Feb 2004 14:18:21 +0000, Ben Morrow wrote:
    >>> But why would someone use a reference if they can use a normal
    >>> variable?


    >> I've read a lot of the other answers in this group, but none of them
    >> seem to relate to why I prefer references: performance.
    >>
    >> Copying the reference to a huge array is always faster than copying the
    >> array itself. It also uses less memory.


    > But the semantics are different. If one is correct, the other is wrong.


    That's correct. But did we all (ie. me, at least) understand what the OP
    really meant?

    "But why would someone use a reference if they can use a normal
    variable?"

    Is that about semantics at all? Maybe I misunderstand a bit, but the as I
    see it, the main point of using references is the performance gain...?


    --
    Tore Aursand <>
    "I didn't have time to write a short letter, so I wrote a long one
    instead." -- Mark Twain
     
    Tore Aursand, Feb 10, 2004
    #18
  19. Thomas Deschepper <> wrote in message news:<c08d6u$89k$>...
    > I've been reading Beginning Per & Programming Perl from O'Reilly for some time
    > now and I'm getting used to references and how to grow them..
    >
    > But why would someone use a reference if they can use a normal variable?


    It's also a convenient way to shortcut to lower branches of complex
    structures. The convenience results from not having to explicitly
    traverse the structure if you know you'll be working primarily in one
    place for a while. For example:

    $kingdom{animalia}{chordata}{mammalia}{artiodactylae}{camelidae}{camelus}{bactrianus}{common_name}
    = "Bactrian Camel";

    If you want to repeatedly refer to the bactrian camel, there's no need
    to keep typing in the entire structure. Just create a reference to
    the hash that holds the information for Bactrian camels:
    $bactrianus_ref = \%{$kingdom{animalia}{chordata}{mammalia}{artiodactylae}{camelidae}{camelus}{bactrianus}};

    Then you can quickly access the attributes of interest:
    print "The common name of Bactrianus is",
    $bactrian_ref->{common_name};

    Or set attributes:
    $batctrian_ref->{hump_count} = 2;

    Yay.
     
    Carlton Brown, Feb 10, 2004
    #19
  20. Thomas Deschepper

    Ala Qumsieh Guest

    "Carlton Brown" <> wrote in message
    news:...

    > It's also a convenient way to shortcut to lower branches of complex
    > structures. The convenience results from not having to explicitly
    > traverse the structure if you know you'll be working primarily in one
    > place for a while. For example:


    Good point.

    > $bactrianus_ref =

    \%{$kingdom{animalia}{chordata}{mammalia}{artiodactylae}{camelidae}{camelus}
    {bactrianus}};

    Why are you de-referencing your reference, and then referencing it again?
    You don't need to do that.

    $bactrianus_ref =
    $kingdom{animalia}{chordata}{mammalia}{artiodactylae}{camelidae}{camelus}{ba
    ctrianus};

    > Then you can quickly access the attributes of interest:
    > print "The common name of Bactrianus is",
    > $bactrian_ref->{common_name};
    >
    > Or set attributes:
    > $batctrian_ref->{hump_count} = 2;


    Assuming you use the correct variable that stores your reference :)

    --Ala
     
    Ala Qumsieh, Feb 10, 2004
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Roger Leigh
    Replies:
    8
    Views:
    474
    Karl Heinz Buchegger
    Nov 17, 2003
  2. Replies:
    3
    Views:
    484
    Victor Bazarov
    Nov 10, 2004
  3. DanielEKFA
    Replies:
    8
    Views:
    641
    DanielEKFA
    May 16, 2005
  4. Mr. SweatyFinger

    why why why why why

    Mr. SweatyFinger, Nov 28, 2006, in forum: ASP .Net
    Replies:
    4
    Views:
    986
    Mark Rae
    Dec 21, 2006
  5. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,238
    Smokey Grindel
    Dec 2, 2006
Loading...

Share This Page