develooper Front page | perl.perl5.porters | Postings from October 1999

A plea for Or-Defined: ordef, |||, |||=

Thread Next
From:
wsnyder
Date:
October 1, 1999 09:35
Subject:
A plea for Or-Defined: ordef, |||, |||=
Message ID:
199910011635.MAA03895@vulcan.maker.com

So, you want to default a value if it's not set, what a great idea!
	my $val1 = shift || "default-value";
	$val2 ||= "default-value";

Or you want to check for errors, also great!
	$foo = sometest() or die "barf";

But, soon you use this on a math function or something which needs the
value 0 and run into the standard problem of the value 0.  So you do one of
the standards:
	my $val1 = (defined $_[0]) ? $_[0] : "default-value";
	$val = "default" if (!defined $val)
	$foo = sometest(); (defined $foo) or die "barf";

All of that nasty repetition of the tested variable seems so anti-perl!
And we all hate extra keystrokes so!

I'd like to suggest 3 new operators
	ordef		(like or)
	|||		(like ||)
	|||=		(like ||=)

Which have the definition of only passing control to evaluate the second
argument if the first is undefined.

Now we have the excellent code: 
	my $val1 = shift ||| "default-value";
	$val2 |||= "default-value";
	$foo = sometest() ordef die "barf";

Note how close it is to the first version which broke on 0 (or ""), which
is the reason for adding all three operators.  Plus the new operators would
generate much better optimized code!

What's the big deal?

Well, looking through the standard modules alone, I found over 80 cases
which could benefit inside ext, then gave up before counting in lib, which
has REAMS of examples!
	
I started hacking this out, but when I got to needing the right version of
byacc I realized that the chances of my getting it right are small.  I'll
plod on if others wish...  (and perhaps for the education also.)

-Wilson

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About