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:
there is just a difference of /i in regular expression assigned to $a and it is producing different outputs.Why?

 



shreyas_007
New User

Jan 30, 2018, 8:57 PM

Post #1 of 3 (4211 views)
there is just a difference of /i in regular expression assigned to $a and it is producing different outputs.Why? Can't Post

#first case
$string = "Cats go Catatonic\nWhen given Catnip";
$a = ($string =~ /when/igm );
($b) = ($string =~ /when/igm );
print "$a and $b \n";

#output for above is
1 and

#second case
$string = "Cats go Catatonic\nWhen given Catnip";
$a = ($string =~ /when/gm ); #here is the only difference
($b) = ($string =~ /when/igm );
print "$a and $b \n";

#output for this is
and When

#the first program does not print the value of $b where as the second #program does.


(This post was edited by shreyas_007 on Jan 30, 2018, 8:59 PM)


FishMonger
Veteran / Moderator

Jan 31, 2018, 8:04 AM

Post #2 of 3 (4194 views)
Re: [shreyas_007] there is just a difference of /i in regular expression assigned to $a and it is producing different outputs.Why? [In reply to] Can't Post

Don't use $a and $b like that even in examples like this. Those are special global vars used by the sort function.

Try reversing the regex's.

Code
c:\test>cat Perl-1.pl 
#!/usr/bin/perl

use warnings;
use strict;

my $string = "Cats go Catatonic\nWhen given Catnip";
my ($word) = ($string =~ /when/igm );
my $cnt = ($string =~ /when/igm );
print "$cnt and $word \n";

c:\test>Perl-1.pl
1 and When



BillKSmith
Veteran

Jan 31, 2018, 8:10 AM

Post #3 of 3 (4193 views)
Re: [shreyas_007] there is just a difference of /i in regular expression assigned to $a and it is producing different outputs.Why? [In reply to] Can't Post

I am not sure what you expect the /g to do. In list context, it returns a list of all matches. In scalar context, it returns the next match. In order for this to work, each search must start where the previous successful search ended. (It resets the starting point when the match fails)

Examine your four examples.

The first succeeds in scalar context. (returns 1, does not
reset starting position)

The second fails because there is no second match. In list context, it returns a single undefined.

The third fails because the case does not match. In scalar context, it returns false and resets the starting position.

The fourth finds and returns all matches (There is only one). This is different from the second example because it starts from the beginning rather than the end of 'When'.
Good Luck,
Bill

 
 


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

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