ralphch has asked for the wisdom of the Perl Monks concerning the following question:

I have a variable that can contain strings such as "New_Features/Some_other_folder". I'm currently using the following match:

if($foo =~ 'Old_Archive') { print "do something"; }

I was wondering if the =~ operator is the fastest and most efficient solution for this sort of matching, or if I should be using a Regex and, if so, which. I basically need to match any string that contains "Old_Archive" or "Old_Archive/something_else" or "Old_Archive/something_else/yet_another_path".

I would also appreciate if you can provide me with a good reference for regular expressions since I'm a little out of practice with them.

Thanks,
Ralph

Replies are listed 'Best First'.
Re: Best method for matching strings
by sgifford (Prior) on Nov 07, 2005 at 01:01 UTC
    friedo and EvanCarroll are right that index will probably be fastest. Still, I wanted to clarify that by using =~, you're using a regex; that's exactly what the =~ operator does. You can learn more about regular expressions in the perlre(1) manpage included with Perl, in any good book on Perl (such as Learning Perl or Programming Perl), or in the O'Reilly book Mastering Regular Expressions.
Re: Best method for matching strings
by EvanCarroll (Chaplain) on Nov 06, 2005 at 23:07 UTC
    I would think index() would be the fastest, though a benchmark is at hand. Check out perldoc -f index.

    UPDATE:

    I must say, I do find it irritating when people post first, are wrong and then modify their post to be an almost direct copy of another post. My suggestion was new, because the first reply by friedo had suggested using substr rather than index. After my post he had changed his. If you want to change your viewpoint/modify your stance on a subject, than at least state that you have UPDATE(d): your node.


    Evan Carroll
    www.EvanCarroll.com
      If you want to change your viewpoint/modify your stance on a subject, than at least state that you have UPDATE(d): your node.

      Ahem... ;-)

      -sauoq
      "My two cents aren't worth a dime.";
      
      My apologies, EvanCarroll. I do usually post an UPDATE when I change a node, but as that was a quick brainfart I immediately changed it from substr to index. Since I changed it within a minute or so of realizing my blunder I didn't feel the need to inform the world of my stupidity.
        All is good, no grudges held. As the adage goes, "happens to the best of us."


        Evan Carroll
        www.EvanCarroll.com
Re: Best method for matching strings
by friedo (Prior) on Nov 06, 2005 at 23:05 UTC
    If all you need to do is match a constant string, (as opposed to a pattern) then it's probably easier and faster to use index. Remember that index returns -1 on failure, since zero is a valid offset.