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

I am using the example program that's in the Learning Perl, 4th Edition

dmathis@radar perl$ cat regexp

#!/usr/bin/perl while (<>) { # take one input line at a time chomp; if (/(dmathis@gmail.\w+)/) { print "Matched: |$`<$&>$'|\n"; # the special match vars } else { print "No match: |$_|\n"; } }


dmathis@radar perl$ ./regexp
I am using dbmathis@domain.com with this example? No match: |I am using dbmathis@domain.com with this example?| I am using dmathis@gmail.org this time. Matched: |I am using <dmathis@gmail>.org this time.|


shouldn't the last output be:

Matched: |I am using <dmathis@gmail.org> this time.|

Replies are listed 'Best First'.
Re: Qwestion about Automatic Match Variables
by Corion (Patriarch) on Sep 22, 2008 at 13:00 UTC

    Using warnings or launching perl with the -w switch would have told you that there is a problem:

    > perl -w tmp.pl Possible unintended interpolation of @gmail in string at tmp.pl line 5 +. Name "main::gmail" used only once: possible typo at tmp.pl line 5. Terminating on signal SIGINT(2)

    ... and using strict would have prevented that error completely as it forces you to predeclare variables:

    > type tmp.pl #!/usr/bin/perl use strict; while (<>) { # take one input line at a time chomp; if (/(dmathis@gmail.\w+)/) { print "Matched: |$`<$&>$'|\n"; # the special match vars } else { print "No match: |$_|\n"; } } > perl -w tmp.pl Possible unintended interpolation of @gmail in string at tmp.pl line 6 +. Global symbol "@gmail" requires explicit package name at tmp.pl line 6 +. Execution of tmp.pl aborted due to compilation errors.

    You need to escape the @ because Perl interprets this as the start of the name of an array:

    ... if (/(dmathis\@gmail.\w+)/) { ...
      lol! That's what I get for copying and pasting :) I always use -w and I just assumed that the code in the book would have it so I never checked.

      Thanks fo rthe pointer.
        Ah - that would also explain why the example in the book contains your email address. ;-)
Re: Qwestion about Automatic Match Variables
by wrinkles (Pilgrim) on Sep 22, 2008 at 14:34 UTC
    You probably want to escape the '.' to prevent matching typos like 'dmathis@gmail,com'
    if (/(dmathis@gmail\.\w+)/) {
    Update: Added the escape. Oops! Hitting "Stop" on my browser apparently didn't stop the form from being submitted on my previous post. Next time I'll be patient and let the browser finish loading, then edit the post. :)
Re: Qwestion about Automatic Match Variables
by wrinkles (Pilgrim) on Sep 22, 2008 at 14:33 UTC
    You probably want to escape the '.' to prevent matching typos like 'dmathis@gmail,com'
    if (/(dmathis@gmail.\w+)/) {