George said:
Hi
I have following command
@ar1=map {if (/\\/) {$_}} @arr;
which populates the ar1 with where it files"\" in @arr BUT it also
appends BLANK records where it does'nt ,
my question is how to avoid appending blank records
The return value of a block is the value of the last expression
evaluated in that block.
In then case of a block where the last statement is an unsatified if
statement without an else clause the last expression executed is the
condition.
$foo = do { if ( 0 ) { 666 } }; # $foo = 0
$foo = do { if ( 0 ) { 666 } else { 777 }; # $foo = 777
$foo = do { if ( 1 ) { 666 } }; # $foo = 666
$foo = do { if ( '' ) { 666 } }; # $foo = ''
$foo = do { if ( undef ) { 666 } }; # $foo = undef
However I would not want to assume this behaviour would never change.
If you want to use an if statement in a non-void context always give it
an appropriate else clause...
@ar1=map { if (/\\/) { $_ } else { () } } @arr;
Of course, if you are goint to put the whole if () {} else {} on one
line it would be more conventional to use ?: instead.
Some people dislike using if in a non-void context altogether - but I
often find that for non-trivial expressions it is less unreadable than
the ?: approach. (Although often factoring-out the inline if altogether
is better still).
my %h = (
THIS => 1,
THAT => 2,
do {
if ( wibble() ) {
( WIBBLE => 'lots of stuff that really would make you' .
'loose track of where the ?: started' );
} else {
();
}
},
OTHER => 777,
);