On Jun 17, 2014, at 1:02 PM, SSC_perl wrote:

>       What's the best way to stop undefined warnings for code like this:
> 
> $data->{'image'} = CopyTempFile('image') if ($main::global->{'admin'} && 
> $main::global->{'form'}->{'image_upload'} ne '');
> 
>       CGI::Carp gives the following:
> 
> [Tue Jun 17 14:54:36 2014] admin.cgi: Use of uninitialized value in string ne 
> at admin.cgi line 219.
> 
>       I know that I can surround the section with 
> { 
> no warnings 'uninitialized';
> ...
> }
> 
> or I could add a check for defined-ness as follows:
> 
> $data->{'image'} = CopyTempFile('image') if ($main::global->{'admin'} && 
> defined $main::global->{'form'}->{'image_upload'} && 
> $main::global->{'form'}->{'image_upload'} ne '');
> 
>       Is there a better way to stop this warning in situations like this?  
> I'd like to keep these warnings from filling up the log.

"Best" and "better" are subjective terms about which people will argue.

Me, I would split your one, long line into several lines and use a temporary 
variable to hold the possibly undefined value and assigning '' to it if it is 
undefined:


  my $upload = $main::global->{'form'}->{'image_upload'} || '';
  if ($main::global->{'admin'} && $upload ne '' ) {
    $data->{'image'} = CopyTempFile('image');
  }


I find that much more readable and will not generate any undefined warnings.

Note that later Perls can use the // operator in the first line to test the 
"definedness" of the hash value:

  my $upload = $main::global->{'form'}->{'image_upload'} // '';


but there is no practical instance in this case. There would be if you needed 
to distinguish zero or '' from undef.


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to