[tpm] Is there a three-way version of...

Uri Guttman uri at StemSystems.com
Sat May 30 12:29:11 PDT 2009

>>>>> "SF" == Shaun Fryer <sfryer at sourcery.ca> writes:

  SF> This is interesting. I learned something new. Now I'm personally
  SF> curious if there's an operator that instead of doing "or equals", does
  SF> "equals or". For instance, I find myself doing this alot (particularly
  SF> in accessors/setters)...

  SF> $x = $y if defined $y;

or you can do:

$x = $y // $x ;

as for accessors/setters i bet you are doing something like this:

sub foo {

	my $self = shift ;
	my $val = shift ;

	$self->{foo} = $val if defined $val ;

	return $self->{foo} ;

that has a minor flaw. you can't tell if val was passed in vs a real
undef was passed in. as in which of these will undef the value?

	foo() ;
	foo( undef ) ;

in the above code, neither will undef it and both do the same thing
which is just return the old value.

the proper solution (which also eliminates your reverse defined or
problem) is to check @_'s length. this way you know if any arg was
passed in for val. there are variations on this but this is one simple

sub foo {
	my( $self, $val ) = @_ ;

# see if any args were passed to foo(). note that the object is first so
# don't count it.

	$self->{foo} = $val if @_ > 1 ;
# another variant is:
#	$self->{foo} = $_[1] if @_ > 1 ;
# and if you shifted out the object then this would work:
#	$self->{foo} = shift if @_ ;

	return $self->{foo} ;


Uri Guttman  ------  uri at stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- http://perlhunter.com/college.html ---------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

More information about the toronto-pm mailing list