LPM: H*lp with undef?

Frank Price fprice at mis.net
Thu Nov 18 19:36:00 CST 1999


On Thu, 18 Nov 1999, David Hempy wrote:

# Okay, I'm a bit stumped here regarding very simple use of a hash.  I want
# to say:
# 
# 	$some_field = $in{"myfield"};				# Line 51
# 	$foo = "Their field has: " . $in{$some_field};		# Line 52

Hmmm... I'm not sure I understand this.  Line 51 assigns the value of
$in{'myfield'} to a scalar.  So $some_field contains either a simple
scalar value, or a reference.  But Line 52 isn't dereferencing the
value ... I'm not sure I understand what this is trying to do...

# Problem is, if there is no $in{"myfield"}, then $some_field is undef, and I
# get:
# 
# 	"Use of uninitialized value at mailform.bat line 52."
# 
# I do not know in advance whether there will be "myfield" or not...it is
# optional.  I had expected the . operator to quietly ignore my attempt to
# concatenate a string and undef, as that seems like a pretty perlish sort of
# thing from what I've seen.  

Do you still get this if you run without the -w flag?

I would approach this from the point where the hash key and value gets
put in.  That is, from whatever section it is where you find out about
'myfield' (presumably it's not from iterating over the keys of %in !),
test $in{'myfield'}:  
   $in{'myfield'} = "no value" unless defined $in{'myfield'};

Alternately, you could do this if you want to keep $in{'myfield'} undefined:

   $somefield = $in{'myfield'} or "";

# The cleanest solution I've come across so far is:
# 
# 	$foo = "Their field has: " . $in{$some_field} if defined($some_field);
# 
# This still seems pretty cludgey, and not nearly as graceful as the scripts
# Rich and Nat share with us.  There are a dozen places I use optional fields
# in this CGI script, and would much rather just use them blindly regardless
# of whether they are undef or not, instead of testing their values all over
# the place.

See, I would think you would want to do something like this, to just
print out the keys and values that /are/ defined and not worry about
those that aren't:

   foreach $key (sort keys %in) {
      print "Their field has: $in{$key}\n";
   }

But I probably don't understand the problem very well :-)

-Frank.
____							    ____
Frank Price					Unix sysadmin, Perl
fprice at mis.net					& Web Programming





More information about the Lexington-pm mailing list