jerrygarciuh has asked for the wisdom of the Perl Monks concerning the following question:

I am curious about how to incorporate an else statment when I have used if in the latter part of a line like so:
foreach (@input){ push @name_nums, $list{ $_ } if exists $list{ $_ }; # }else{ # push (@name_nums,$_); }

Those 2 lines are commented out because the else causes syntax errors. How do I use if in this way and then add an else?
TIA
jg
Ain't no time to hate! Barely time to wait! ~RH

Replies are listed 'Best First'.
Re: If /Else Structure when If is used in latter part of a line.
by lestrrat (Deacon) on Sep 30, 2001 at 21:00 UTC

    You can't. Just use the normal expression :

    foreach (@input) { if( exists $list{ $_ } ) { push @name_nums, $list{$_}; } else { push @name_names, $_; } }

    TMTOWTDI :

    foreach my $input (@input ) { push @name_nums, ( exists $list{ $input } ? $list{ $input } : $in +put ); } ## following will not work if $list{ $input } can be 0 or undef, ## but here's another way foreach my $input ( @input ) { push @name_nums, ( $list{ $input } || $input ); }
Re: If /Else Structure when If is used in latter part of a line.
by demerphq (Chancellor) on Sep 30, 2001 at 21:33 UTC
    Hi Jerry

    The simple answer is, you cant.

    A better answer is that an if statement used as you have done is not a compund if statement, but an if statement modifier (see perlsyn). Consider

    my $x=1 if $y; # statement modifier if ($y) {my $x=1} # compund statement
    The two are very different. The first declares $x to be in scope and if $y is true initializes it to 1. The second checks to see if $y is true, then declares $x to be equal to 1 _within_ its own scope, so $x wont be available after the if completes.

    But it seems to me that what you want is one of the two following snippets.

    # first variant, dont do this. foreach (@input){ push @name_nums, (exists $list{$_}) ? $list{ $_ } : $_; } # second variant, do this @name_nums=map{(exists $list{$_}) ? $list{ $_ } : $_}@input;
    This is precisely the task that map was invented for. Basically apply a function to every element of an array putting the results in another array.

    Update The solutions above use the secret third kind of if. Its called the Conditional Operator or sometime the ternary operator and works like this:
    condition ? result : other result
    Where result and other result are evaluated for the value they return. This can very useful when you need an if in a place where normally an if is prohibitied. You may need to add parenthesis depending on the situation. An example is below:

    print "Hello my name is ".(defined $name ? $name : "Anonymous Monk")." +\n";
    HTH

    Yves
    --
    You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)