For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > April 2005 > default value from match









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author default value from match
Keith Worthington

2005-04-20, 3:56 pm

Hi All,

I am still slugging it out. Many thanks to those that have helped me thus
far. :-)

Having written the following code I am now troubled by v_feet_str or
v_inch_str being undefined. If there is no match can I return a default
value? In my case if there is no dimension then I want to move ahead using a
zero in that position.

($v_dim1_str, $v_dim2_str) = split(/\s*x\s*/i, $v_size_str);
# Now split dimension one into feet and inch parts.
#my ($v_feet_str, $v_inch_str) = split(/(?:'|")/, $v_dim1_str);
$v_dim1_str =~ /\s*([\d\.\s\-\/]+)\s*'\s*([\d\.\s\-\/]+)\s*"/;
my ($v_feet_str, $v_inch_str) = ($1, $2);
print "Dimension 1\n";
print " Feet: $v_feet_str\n";
print " Inches: $v_inch_str\n";

Kind Regards,
Keith

Chris Devers

2005-04-20, 3:56 pm

On Wed, 20 Apr 2005, Keith Worthington wrote:

> Having written the following code I am now troubled by v_feet_str or
> v_inch_str being undefined. If there is no match can I return a
> default value? In my case if there is no dimension then I want to
> move ahead using a zero in that position.


The usual idom for this is something like

$foo = defined $foo ? $foo : 0;

Or maybe

$foo ||= 0;

Or maybe simply

$foo += 0;

I think I like the last one best. It's short, clear, and should do the
right thing for you.

(Skipping ahead a bit, Perl6 , if I remember right, is going to have the
'//' operator that tries to solve this sort of problem, allowing you to
set a value for a variable if & only if it wasn't already defined. But
it'll be a little while before this is available, though you can start
playing around with things like this using the Perl6::* CPAN modules.)



--
Chris Devers
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com