[tpm] Pub discussion (1)

Jim Harris ja_harris at rogers.com
Thu Aug 28 21:08:30 PDT 2008


The variables get set the same either way.  The difference is that shift changes the value of @_, and the other way does not.


--- On Fri, 8/29/08, Alex Beamish <talexb at gmail.com> wrote:
From: Alex Beamish <talexb at gmail.com>
Subject: [tpm] Pub discussion (1)
To: "tpm" <tpm at to.pm.org>
Received: Friday, August 29, 2008, 3:46 AM

Greetings,

After Madison's presentation on Net::DBus tonight, we retreated to
Burgundy's where a number of interesting technical discussions popped
up. Among them were discussions as to whether

    my $self = shift;
    my $value = shift;

would mean changes to $self would be reflected the same way than if
$self and $value were collected in
 one fell swoop using

    my ( $self, $value ) = @_;

My experiments consisted of three files, Obj1.pm:

package Obj1;

sub new
{
    my $class = shift;
    my $self = {};

    bless ( $self, $class );
    return ( $self );
}

sub add
{
    my $self = shift;
    my $value = shift;

    $self->{value} = $value;
}

sub value
{
    my $self = shift;
    return ( $self->{value} );
}

1;

And the almost identical Obj2.pm:

package Obj2;

sub new
{
    my $class = shift;
    my $self = {};

    bless ( $self, $class );
    return ( $self );
}

sub add
{
    my ( $self, $value ) = @_;

    $self->{value} = $value;
}

sub value
{
    my $self = shift;
    return ( $self->{value} );
}

1;

And finally the test script:

#!/usr/bin/perl -w
#
#  Test creating
 Obj1 and Obj2 to see if methods that access arguments
#  differently affect whether changes propogate back to the caller.
#  Specifically, does
#
#    my $self = shift;
#    my ( $vars ) = @_;
#
#  produce a different result than
#
#    my ( $self, $vars ) = @_;

use Obj1;
use Obj2;

{
    my $obj1 = Obj1->new();
    $obj1->add("This is object one");
    print "Obj1 value is " . $obj1->value() . "\n";

    my $obj2 = Obj2->new();
    $obj2->add("This is object two");
    print "Obj2 value is " . $obj2->value() . "\n";
}

The resulting output of running test12.pl is

[alex at foo tpm-August2008]$ perl -w test12.pl
Obj1 value is This is object one
Obj2 value is This is object two

This suggests that both methods (two shifts, or a single pull from @_)
produce the same results.

Have I misunderstood, or coded something incorrectly? I believe
 that
both approaches mean pass by reference, meaning that changes are
reflected.

-- 
Alex Beamish
Toronto, Ontario
aka talexb
_______________________________________________
toronto-pm mailing list
toronto-pm at pm.org
http://mail.pm.org/mailman/listinfo/toronto-pm
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20080828/ff7b3cb5/attachment.html>


More information about the toronto-pm mailing list