CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Intermediate:
Clarification on assigning an array referent to a variable



Oct 16, 2000, 6:53 PM

Post #1 of 2 (539 views)
Clarification on assigning an array referent to a variable Can't Post

Hello all, I was hoping someone could help me understand this code
example I came accross in Damian Conway's "Object Oriented Perl." :

# Begin Code snippet...

sub Projectile::get_velocity
my ($self) = @_;
return $self->[2]/$self->[11];

Ok, I can see the end result, $self->[2] accesses the 3rd element of
the array (gotten from the argument list passed to the sub) referred to
by $self.

What puzzles me is the assignment. How does $self reference an array
given the method by which it was assigned to? @_ is an array --
given. But to assign a reference, I thought you had to use the syntax:

my $self = \@_;

Shouldn't $self remain a plain scalar value and contain only the last
element of the @_ array?

If someone could give me a little blub explaining the logistics as to
why the first code snippet I cited works, I'd really appreciate it. No
dissertation needed (don't want to cause someone unecessary typing),
I'm pretty quick to catch on, but I'm a little stumped on this one.

Thanks all.


Oct 16, 2000, 7:16 PM

Post #2 of 2 (539 views)
Re: Clarification on assigning an array referent to a variable [In reply to] Can't Post

The point is that the get_velocity() method of a Projectile class gets a Projectile object as its first argument. That object is (in this case) an array reference. So $_[0] is the object, which is a reference to an array.

Try this:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

package Foo;
sub new { bless [] }
sub method {
my ($self) = @_;
print "$self ", ref($self), "\n";

package main;
$x = Foo->new();

It'll print something like:

Foo=ARRAY(0x12345) Foo

The BIG point here is that you're assigning to a list of values. Doing

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

my ($x) = @_;

is like saying

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

my $x = $_[0];

The first element of @_ is, for object methods, the object itself.

Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives