in reply to Subroutine question on use of uninitialized value.

exists
sub send_values { my ($args) = @_; my @params = qw( name address pic id zip phone ); my $values = "Your Results are:\n"; for (@params) { $values .= "$args->{$_}\n" if exists $args->{$_}; } }

Replies are listed 'Best First'.
Re^2: Subroutine question on use of uninitialized value.
by sauoq (Abbot) on Jun 01, 2012 at 14:20 UTC
    $ perl -we 'my $h={k=>undef}; print $h->{k} if exists $h->{k}' Use of uninitialized value in print at -e line 1.

    This is why defined() may be preferable.

    -sauoq
    "My two cents aren't worth a dime.";
Re^2: Subroutine question on use of uninitialized value.
by Anonymous Monk on Jun 01, 2012 at 13:48 UTC
    Would be possible to have it without a loop, I need to make a small xml with these values like:
    my $value = "<results> <name>$args->{name}</name> <address>$args->{address}</address> ... </results> ";
    I was thinking about checking right at this first line:
    my ($args) = @_;

    Thanks!
      Would be possible to have it without a loop
      What's wrong with loops? They're low in fat, high in fiber... oh, nevermind.
      use warnings; use strict; my $info = send_values({ name => 5, address => 6, id => 7, pic => 8, }); print $info; sub send_values { my ($args) = @_; my @params = qw( name address pic id zip phone ); my $values = "<results>\n"; for (@params) { $values .= " <$_>$args->{$_}</$_>\n" if exists $args->{$_ +}; } $values .= "</results>\n"; return $values; } __END__ <results> <name>5</name> <address>6</address> <pic>8</pic> <id>7</id> </results>

      You could do the above without a loop, but it wouldn't be as scalable or as easy to maintain. For example, you would have to type 'address' 4 times instead of once:

      $values .= " <address>$args->{address}</address>\n" if ex +ists $args->{address};