develooper Front page | perl.fwp | Postings from December 2001

Re: tri-state flags

Thread Previous
Lars Henrik Mathiesen
December 5, 2001 11:54
Re: tri-state flags
Message ID: () writes:
>On Wed, Dec 05, 2001 at 11:44:30AM -0500, Martin 'Kingpin' Thurn wrote:
>> How about
>> (eval{$flag} eq '0')

>That triggers a warning if $flag is undefined. If one doesn't care
>about warnings, "$flag eq 0" would do too. However, it's doesn't
>return true on "", which turned out to be required.

There seems to be very few constructions in Perl that distinguish
between undef and '' silently under -w --- apart from defined(), of

Experiment shows that hash lookups don't like undef either, unless the
hash is empty. Or unless it's a symbol table lookup like $$x:

	tyr 37 >cat tmp/
	#!/usr/bin/perl -w

	use strict;
	no strict 'refs';

	*{''} = *{0};

	sub test { my $flag = shift; \$$flag == \${''} }

	# Aborts on undef: sub test { \${(shift)} == \${''} }

	sub show {
	    my $flag = shift;
		   defined $flag ? "'$flag'" : 'undef',
		   (test $flag) ? 'true' : 'false');

	show undef;
	show '';
	show 0;
	show "0";
	show 1;
	show "1";
	tyr 38 >tmp/
	undef false
	''    true
	'0'   true
	'0'   true
	'1'   false
	'1'   false
	tyr 39 >perl -v

	This is perl, v5.6.0 built for i686-linux

This test only uses the value once, but it still needs a tempvar,
since it aborts on undef if using an expression. (Not checking for
undef on scalar string ref lookup of a simple scalar variable is
arguably an inconsistency that should be fixed).

And since Bart seemed to want something he could wrap around an
arbitrary expression, this is not quite it yet.

Lars Mathiesen (U of Copenhagen CS Dep) <> (Humour NOT marked)

Thread Previous Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About