RE explanation

N

Noname

Hi
I have following re
$Test="5-15";
my (@sid)= ($Test=~/(\d+)-(\d+)/?($1..$2):$_);
which polulate the @sid with 5 to 15 numbers,
what I don't understand is
?($1..$2):$_) how does this work
 
A

A. Sinan Unur

Hi
I have following re
$Test="5-15";
my (@sid)= ($Test=~/(\d+)-(\d+)/?($1..$2):$_);
which polulate the @sid with 5 to 15 numbers,
what I don't understand is
?($1..$2):$_) how does this work

Please do not ask thousands of people to read the documentation for you.

From

perldoc perlop:

Conditional Operator
Ternary "?:" is the conditional operator, just as in C. It works much
like an if-then-else. If the argument before the ? is true, the
argument before the : is returned, otherwise the argument after the :
is returned.

Now, I personally would hope that I would never write anything like
this. Assuming $_ supposedly holds some default value, I would re-write
this as:

#! perl

use strict;
use warnings;

my $default = 1;
my $test = '5-15';
my @range;

if($test =~ /^(\d+)-(\d+)$/) {
@range = ($1 .. $2);
} else {
@range = ($default);
}

print "@range\n";

__END__

I don't know where the $test string is coming from, but you probably
want to perform some additional bounds checking on the variables. What
happens to your program if $test contains:

'0-2000000000'

Sinan
 

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,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top