Why references??

  • Thread starter Thomas Deschepper
  • Start date
T

Thomas Deschepper

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
 
W

Walter Roberson

: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.
 
B

Ben Morrow

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
 
C

ctcgag

Thomas Deschepper said:
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
 
W

Walter Roberson

:[email protected] (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.
 
M

Malcolm Dew-Jones

Thomas Deschepper ([email protected]) 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?
 
B

Ben Morrow

:[email protected] (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
 
B

Brad Baxter

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
 
A

Ala Qumsieh

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
 
B

Ben Morrow

Ala Qumsieh said:
errr .. those two are not the same.


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
 
A

Ala Qumsieh

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
 
J

Jürgen Exner

Thomas said:
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
 
M

Matthew Braid

Thomas said:
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
 
T

Thomas Deschepper

[Monday 09 February 2004 17:41]Thomas Deschepper
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 ;)
 
T

Tore Aursand

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".
 
B

Ben Morrow

Tore Aursand said:
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
 
J

Jürgen Exner

Tore Aursand said:
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
 
T

Tore Aursand

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...?
 
C

Carlton Brown

Thomas Deschepper said:
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.
 
A

Ala Qumsieh

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top