$1 appears to be localised into the function that calls the regexp. In this case, that's some anonymous function created somewhere inside of Switch.pm.

If you still want to use Switch, and you can't stand the repetition, try the following:

my $dollar1; case /^\s*(\S+)$ (?{ $dollar1 = $1 })/ { ...

I don't have Switch, so I didn't test the above. Here's a proof of concept, though:

use strict; use warnings; sub do_re { my ($re, $var) = @_; $var =~ /$re/; print("inside: $1\n"); } { my $re = qr/(b)/; print("$re\n"); do_re($re, 'abc'); if (defined($1)) { print("outside: $1\n"); } else { print("outside: [undef]\n"); } } print("\n"); { my $dollar1; my $re = qr/(e)(?{ $dollar1 = $1 })/; print("$re\n"); do_re($re, 'def'); if (defined($dollar1)) { print("outside: $dollar1\n"); } else { print("outside: [undef]\n"); } } __END__ (?-xism:(b)) inside: b outside: [undef] (?-xism:(e)(?{ $dollar1 = $1 })) inside: e outside: e

I wasn't sure if it would use the lexical $dollar1 instead of the package variable by the same name, but it does.


In reply to Re: Switch and $1? by ikegami
in thread Switch and $1? by pianogirl95

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.