in reply to Undef and Unitialized Issue

In more general terms, I typically use something like this to silence those warnings (assuming a value of undef is not an error):

my $string_var = defined( $input_field ) || ''; # or if ( ($string_var || '') !~ /some_pattern/ ) { ... }
If in fact undef is an error I would generally use something along this line:
croak "HEY! Why am I not defined?" if !defined( $input_field );

You must always remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.

Replies are listed 'Best First'.
Re^2: Undef and Unitialized Issue
by afoken (Chancellor) on Apr 04, 2015 at 09:11 UTC
    my $string_var = defined( $input_field ) || '';

    This will set $string_var either to 1 or to "", no matter what $input_field was set to. Looking at the variable names, this is hardly what you want.

    ($string_var || '')

    This evaluates to "" if $string_var is undef, 0, or "0". You don't want to change "0" or 0 to the empty string, do you?

    Why don't you use the defined-or operator //? $string_var//'' evaluates to "" only if $string_var is "" or undef. 0 and "0" are not changed.

    Ancient perl versions have no defined-or-operator, so you have to resort to something like $never_undef=defined($perhaps_undef) ? $perhaps_undef : ''; for code that is expected to work with ancient perl verisons.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

      You are correct, I was thinking of where I use delete($input) || '' to ensure a defined value and "0" is not a concern. The second form you present (using ?:) is more correct in the general case.

      As for using an "ancient version of Perl" I don't have a choice at $work, we are stuck on 5.8.9 for at least a few more months.

      You must always remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.