Regular Expression Annoyance

Tom Hukins tom at
Thu Jun 10 05:41:30 PDT 2010


I'm writing a Test::WWW::Mechanize script to help me test the Web
interface to one of the systems I babysit.

I have something like the following:
  $mech->content_unlike( qr/Error: ([^>]+)/, 'No error message' );
  diag $1 if $1;

So, if my test script encounters an error, I get to see it.  At least,
that's the plan.  But $1 never contains anything.

Here's why:
  perl -E 'sub foo { $_[0] =~ /Hi (\w+)/; } foo("Hi Tom"); say "Hello $1";'

$1 doesn't exist in the scope I diag() or say() in because the regular
expression ran in a different scope.  This makes sense:  generally, I
wouldn't want different scopes to interfere with each other.

So I've written:
  $mech->content_unlike( qr/Error: ([^>]+)/, 'No error message' ) ||
    $mech->content() =~ qr/Error: ([^>]+)/ &&
    diag $1;

But that feels horrid and long winded.  I like writing succinct,
expressive code.  And I can't figure out how.  Please help.


More information about the MiltonKeynes-pm mailing list