CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Basic perl question

 



heman
New User

Aug 5, 2014, 12:15 PM

Post #1 of 3 (996 views)
Basic perl question Can't Post

Hi Guys,
I'm a beginner at perl. I'm trying to do some regular expressions with conditions

my @a = ("A","B","C");

foreach $b(@a) {
if(($b !~ /A/)||($b !~ /C/)) {
printf ("$b \n");
}
else {
printf ("@a $b\n");
}
}

I see the result as:
A
B
C

However, I'm expecting
A
A B C B
C

If i change the code to

my @a = ("A","B","C");

foreach $b(@a) {
if($b !~ /A/) {
printf ("$b \n");
}
else {
printf ("@a $b\n");
}
}
Then the not equal to condition is doing as expected giving me following results:
A B C A
B
C

I'm not sure why adding 2 "not equal" conditions makes this behave wrong!

Thanks,
Heman :)


BillKSmith
Veteran

Aug 5, 2014, 1:44 PM

Post #2 of 3 (988 views)
Re: [heman] Basic perl question [In reply to] Can't Post

Perl is doing what your code says.
There are three cases:

$b contains 'A'

The first expression is false because the regex does match, but the second is true because the regex fails to match. Logical or makes the result 'TRUE'.

$b contains 'B'

The first expression is true because the match fails. With the logical or, it is not even necessary to evaluate the second expression. The result is 'TRUE'

$b contains 'C'

Like the previous case, the first expression is true. The result is 'TRUE'



The following will produce the desired output:


Code
my @a = ( "A", "B", "C" ); 

foreach $b (@a) {
if ( ( $b =~ /A/ ) || ( $b =~ /C/ ) ) {
printf("$b \n");
}
else {
printf("@a $b\n");
}
}


Again look at the three cases

$a contains 'A'

The first expression is true. The result is 'TRUE'.

$b contains 'B'

Neither expression matches, so both expressions are false. The result is 'FALSE'

$b contains 'C'

The first expression is false, but the second is true. The result is 'TRUE'
Good Luck,
Bill


heman
New User

Aug 5, 2014, 2:02 PM

Post #3 of 3 (985 views)
Re: [heman] Basic perl question [In reply to] Can't Post

Thanks Bill.
Now i see what i was missing :(

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives