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

Hello,
If i was to store a pattern i was looking for in a string from input:
$match = <STDIN>;
What is required in:
$_ =~ /$match/;
This does not appear to work?
Thanks,

janitored by ybiC: Retitle from "regex" as one-word nodetitles hinder site searching, also minor format cleanup

Replies are listed 'Best First'.
Re: Using a regex pattern from STDIN
by pbeckingham (Parson) on Jun 21, 2004 at 15:48 UTC

    Could it be that when you read from <STDIN> you are getting an automatic newline character that is affecting your search? Try chomp. qr may be of interest to you as well.

Re: Using a regex pattern from STDIN
by Limbic~Region (Chancellor) on Jun 21, 2004 at 15:53 UTC
    Anonymous Monk,
    In addition to the trailing newline that you need to chomp offered by pbeckingham, you need to be aware that any meta-characters in the regex need to be escaped if they are not intended to be meta-characters.
    my $re = <STDIN>; chomp $re; $re = quotemeta $re; print "it worked" if $foo =~ /$re/;
    Cheers - L~R
      If this script is to be used by other users (besides you), you should be aware that it's dangerous to use user-entered data without untainting it first. Use 'taint' mode by doing
      #!/usr/bin/perl -wT
      the "T" means "T"aint mode - it won't allow you to use any data from outside your program unless you untaint it first.
        Use 'taint' mode by doing #!/usr/bin/perl -wT

        That's almost good advice. Adding Taint Checking can't be done on the shebang line because it is already too late. You need to invoke Perl as perl -T from the command line - see perldoc perlsec. I would argue that you should enable Taint Checking even if you are the only one using the code because things change over time and we are all forgetful without our daily dose of caffeine. I would also say that it is pointless to turn on Taint Checking if you aren't going to take the time to perform "good" untainting regexes and just allow everything through anyway.

        Cheers - L~R

        Update: Ok, and what I said is almost right. As a a kind monk pointed out to me in a /msg, it does do the "right thing" if it is a CGI or as ./scrip.pl, just not from perl script.pl.