in reply to Getting regular expression right

The first one is true if, and only if, there is a colon in the string (assuming no newlines in the string). Hence, the second alternative will never be selected. If that would match, the first alternative would have matched already.

I'd do something like:

if (/$_[0] =~ /^([^:]+):([^|]+)(?:\|(.*))?$/ || $_[0] =~ /^([^|)+)\|(.*)$/) { @key{qw /name definition altdefinition/} = ($1, $2, defined $3 ? $ +3 : "") }
It would even be simpler if you used one kind of delimiter, say the pipe. Then you could do:
if ($_[0] =~ /\|/) { @key{qw /name definition altdefinition/} = split /\|/, $_[0]; $key{altdefinition} = "" unless defined $key{altdefinition}; }
I certainly wouldn't call by sub 'split'.

Replies are listed 'Best First'.
Re^2: Getting regular expression right
by mellin (Scribe) on Feb 15, 2005 at 12:06 UTC
    if (/$_[0] =~ /^([^:]+):([^|]+)(?:\|(.*))?$/ || $_[0] =~ /^([^|)+)\|(.*)$/) { @key{qw /name definition altdefinition/} = ($1, $2, defined $3 ? $ +3 : "") }
    I cannot get this example working? And should @key be %key?
      I cannot get this example working?

      If you say so. Why not? No match? Error? Match when it shouldn't? Wrong content of variables? Explain yourself.

      And should @key be %key?

      No.

        There seems to be error with the regex.

        Error when pasted to my script:
        [mellimik@localhost cgi-bin]$ perl -cw formCreator.pl Scalar found where operator expected at formCreator.pl line 286, near +"?:\|(.*))?$/" (Missing operator before $/?) syntax error at formCreator.pl line 286, near "[^" formCreator.pl had compilation errors.
        It's the character class inside the second last memory parentheses:
        if (/$_[0] =~ /^([^:]+):([^|]+)(?:\|(.*))?$/ || $_[0] =~ /^([^|)+)\|(.*)$/) {
        Should be like this:
        if (/$_[0] =~ /^([^:]+):([^|]+)(?:\|(.*))?$/ || $_[0] =~ /^([^|])+)\|(.*)$/) {
Re^2: Getting regular expression right
by mellin (Scribe) on Feb 15, 2005 at 11:03 UTC
    Thanks. Calling the sub 'split' was just temporarily insanity :) In the real script it's called 'extra'.