rvosa has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I have a question about the '=' operator :-)

I caught myself doing the following:
sub path_to_root { my $self = shift; my $path = $self->get_branch_length; while ( $self ) { if ( $self->get_parent ) { $self = $self->get_parent; $path += $self->get_branch_length; } else { return $path; } } }
That is to say, I make the $self->get_parent method call twice, once to check if there really is a parent, the second time to step to that parent during my traversal (here we're traversing a tree from initial node $self to the root, but this issue is more broadly applicable, obviously).

So if we do an assignment, what value is returned that I can test? Is it the left hand value - i.e. would the following be equivalent, but more efficient?
sub path_to_root { my $self = shift; my $path = $self->get_branch_length; while ( $self ) { if ( $self = $self->get_parent ) { $path += $self->get_branch_length; } else { return $path; } } }

Replies are listed 'Best First'.
Re: assignment operator return values
by Aristotle (Chancellor) on Feb 22, 2006 at 01:30 UTC

    Yes, that works as you expect. Assignments read from right to left, ie. $x = $y = $z = 10 assigns 10 to $z, then assigns the value of $z to $y, then the value of $y to $x – so all three variables end up with the value 10.

    However, the code you want this for can be written cleaner without inline assignment:

    sub path_to_root { my $self = shift; my $path = $self->get_branch_length; my $parent = $self->get_parent; while ( $parent ) { $path += $parent->get_branch_length; $parent = $parent->get_parent; } return $path; }

    Makeshifts last the longest.

Re: assignment operator return values
by GrandFather (Saint) on Feb 22, 2006 at 01:29 UTC

    perlop - Assignment Operators may help. The assignment operator returns the object assigned to as an lvalue so your assignement and test is fine.

    Update:

    I'd be inclined to rewrite that as:

    while ( $self ) { $path += $self->get_branch_length if $self = $self->get_parent; } return $path;

    DWIM is Perl's answer to Gödel
Re: assignment operator return values
by QM (Parson) on Feb 22, 2006 at 01:34 UTC
    TIAS: Try It And See.

    Not to be too onerous, but you've given enough info to test it yourself. Why not just do this?

    C:\>perl -demo Loading DB routines from perl5db.pl version 1.28 Editor support available. Enter h or `h h' for help, or `perldoc perldebug' for more help. main::(-e:1): mo DB<1> for (-1..1) { print "$_"; print "\tTrue" if ($x = $_); print " +\n" } -1 True 0 1 True DB<2>
    And there you have it.

    But what happens when get_parent returns a false value? Here it seems OK, as $self is lexical to this sub. In other situations, you might not want to overwrite $self.

    Yes, the assignment is done, and you can then test for it.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of