harsha.reddy has asked for the wisdom of the Perl Monks concerning the following question:

Hi All
#!/usr/bin/perl -w sub func { my $CmdSep = ($^O =~ m/MSWin32/ig)? "\&" : "\;"; print "The Command Seperator is: " . $CmdSep ."\n"; } func(); func();
The output of this snippet is strange:

perl test.pl
The Command Seperator is: &
The Command Seperator is: ;

This is a very strange behaviour, I am confused that this is a feature or a BUG ;)
Tested using:

This is perl, v5.8.8 built for MSWin32-x86-multi-thread
(with 50 registered patches, see perl -V for more detail)

Copyright 1987-2006, Larry Wall

Binary build 820 274739 provided by ActiveState http://www.ActiveState.com
Built Jan 23 2007 15:57:46

Replies are listed 'Best First'.
Re: flip flop behaviour of regex match
by ikegami (Patriarch) on Oct 10, 2007 at 14:15 UTC

    You're using the g option on the match operator when you don't mean to do so. m//g acts as an iterator in scalar context.

    $_ = 'abc'; print /(.)/g ? $1 : '[]', "\n"; # a print /(.)/g ? $1 : '[]', "\n"; # b print /(.)/g ? $1 : '[]', "\n"; # c print /(.)/g ? $1 : '[]', "\n"; # [] print /(.)/g ? $1 : '[]', "\n"; # a
    $_ = 'abc'; print /(.)/ ? $1 : '[]', "\n"; # a print /(.)/ ? $1 : '[]', "\n"; # a print /(.)/ ? $1 : '[]', "\n"; # a print /(.)/ ? $1 : '[]', "\n"; # a print /(.)/ ? $1 : '[]', "\n"; # a
Re: flip flop behaviour of regex match
by mwah (Hermit) on Oct 10, 2007 at 14:36 UTC
    As ikegami pointed out, /g in scalar context
    doesn't reset pos. Your example will work fine
    after some small modifications, eg.:
    ... sub func { print 'The Command Seperator is: ', $^O =~ /MSWin32/i ? '&' : ';', " +\n" } func(); func(); ...


    <Addendum>
    After thinking about an idiomatic switch between alternatives
    I got this one, which I like somehow:
    sub func { print 'The Command Seperator is: ', qw(; &)[ $^O =~ /MSWin32/i ], "\n" }
    which evaluates the regex in scalar context as 0/1 (array index of the qw...)

    </Addendum>

    Regards

    mwa
      Hi ikegami and mwa
      
      Wow awesome!! this is a super cool feature.
      
      Thanks a lot.