Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: use of constants in regex substitutions?

by edan (Curate)
on Sep 23, 2003 at 11:27 UTC ( [id://293461]=note: print w/replies, xml ) Need Help??


in reply to use of constants in regex substitutions?

use constant {
    MIF_EXTENSION => "\.mif",
    TXT_EXTENSION => "\.txt"
};

This is not doing what you want it to. The backslash is interpreted when perl parses the double-quoted string, so the values end up being '.mif' and '.tif' (since \. has no special meaning in a double-quoted string, as does, say \n). Your regexp will then match any character followed by txt. You need to either:

  1. Put the extensions in single-quoted strings, so the backslash is preserved.
  2. Put \Q and \E in your substitution to disable pattern metacharacters (see perlre for more info if you don't know what that means). Example:
    $s1 =~ s/\Q${\TXT_EXTENSION}\E/MIF_EXTENSION/e;

I personally recommend #2, since you want to match literal text, without metacharacters, and that's what \Q is for.

Also, you should follow Zaxo's advice, and not dmitri's, since one will work, and one won't (you guess which is which).

--
3dan

  • Comment on Re: use of constants in regex substitutions?

Replies are listed 'Best First'.
Re: use of constants in regex substitutions?
by Abigail-II (Bishop) on Sep 23, 2003 at 15:04 UTC
    I'd prefer to write:
    MIF_EXTENSION => "[.]mif", TXT_EXTENSION => "[.]txt",
    Then you don't have to wonder how many backslashes you need, and you don't have to use \Q, \E each time you use MIF_EXTENSION or TXT_EXTENSION.

    Abigail

      Ah, but it doesn't appear that these constants are only being used as the match expression of a regex. For instance, the original code posted is trying to substitute TXT_EXTENSION for MIF_EXTENSION. I don't think the intent is to turn ".txt" into "[.]mif".

      --
      3dan

        Oh, sure, but then your first suggestion, putting them in single quotes isn't going to work either, because I don't think the intent is to turn '.txt' into '\.mif'.

        Abigail

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://293461]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-19 05:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found