map function problem

G

George Kinley

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
 
A

Anno Siegel

George Kinley 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

Using map? That would be

my @ar1=map /\\/ ? $_ : (), @arr;

but that's really a job for grep:

my @ar1 = grep /\\/, @arr;

Anno
 
B

Brian McCauley

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,
);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top