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

Hi Monks,
use constant NAME => "abc"; # read some user input my $input = $ARGV[0]; # I need to check if the input string contains my constant # Something like the following is what I need: if ($input =~ /NAME/) { print "Matched!"; }
The problem with the above is that it treats the NAME in the 'if' line as plaintext, rather than the constant I defined. I know I could do something like -
my $name = NAME; if ($input =~ /$name/) { ... }
but I want to avoid that variable. So 2 questions for the enlightened ones here -
1) How do I use constants in regex matching lines?
2) How do I use constants in search and replace lines?

Thanks in advance for the help!

Replies are listed 'Best First'.
Re: using constants in regex/search
by f00li5h (Chaplain) on Dec 02, 2008 at 04:52 UTC

    use constant'ed constants are really subs that just return the same thing each time... there's no un-nasty way to interpolate them. TheDamian's perl best practices recommends using Readonly for constants for this reason.

    Also  $input =~ /@{[ NAME ]}/ ... but if you do that, the maintenence programmer after you will hunt you down with a hatchet and do unspeakable things to you.

    Enjoy ^_^

    @_=qw; ask f00li5h to appear and remain for a moment of pretend better than a lifetime;;s;;@_[map hex,split'',B204316D8C2A4516DE];;y/05/os/&print;

      Thanks! :)
Re: using constants in regex/search
by plobsing (Friar) on Dec 02, 2008 at 14:46 UTC

    I realize that your example is most likely reduced from something more interesting. However, in this case, another solution exists. Treat the constant as a regex (well a runtime-interpolated search pattern really) in stead of interpolating it into one. Example:

    use constant NAME => 'abc'; # ... if ($input =~ NAME) { print "Matched!" }
Re: using constants in regex/search
by JavaFan (Canon) on Dec 02, 2008 at 09:50 UTC
    I typically use:
    my $NAME = "abc"; ... if ($input =~ /$NAME/) { ... }
    It does use a variable, but it saves a sub. The advantage of being able to interpolate variables to me outweight the advantages 'constants' give me.
      You can use like this
      if ($input =~ /${\NAME}/) { print "Matched!"; }
        That's identical to
        if ($input =~ /$NAME/) {...}
        which is what I used, so I don't get your point.