switch case (/regex/) ... $1 - emtpy

Discussion in 'Perl Misc' started by Petr Sezemsky, Sep 29, 2009.

  1. Hi,

    Why using the regex in switch - case doesn't fill the $1, $2, ..
    variables? This code works as I expect:

    #!/usr/bin/perl
    $_ = "hello world";

    if (/he(ll)o/) {
    print "OK: $1\n";
    }

    but the next doesn't work as the previous:

    #!/usr/bin/perl
    use Switch;
    $_ = "hello world";

    switch ($_) {
    case (/he(ll)o/) {
    print "OK: $1\n";
    }
    }

    Thank you for explanation the problem.

    Petr
    Petr Sezemsky, Sep 29, 2009
    #1
    1. Advertising

  2. Petr Sezemsky

    Uri Guttman Guest

    >>>>> "PS" == Petr Sezemsky <> writes:

    PS> Why using the regex in switch - case doesn't fill the $1, $2, ..
    PS> variables? This code works as I expect:

    PS> #!/usr/bin/perl
    PS> use Switch;

    that module does source filtering. the actual code that compiles is not
    what you put in the file. and because of that it is not recommended to
    ever use that module.

    PS> $_ = "hello world";

    PS> switch ($_) {
    PS> case (/he(ll)o/) {
    PS> print "OK: $1\n";

    you can't easily tell what the code is there and whether the regex is
    run just before your print. it appears how you like it but it isn't
    underneath.

    perl 5.10 has given/when built in (taken from perl6) which is a proper
    switch statement and it supports smart matching as well. this works as
    you expect:

    perl -le 'use feature ":5.10"; given ("bar") { when( /(a)/ ) { print "$1\n" } }'
    a

    see the docs in perlsyn for the full syntax.

    uri
    Uri Guttman, Sep 29, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. ad
    Replies:
    1
    Views:
    1,299
    =?Utf-8?B?c2VyZ2UgY2FsZGVyYXJh?=
    Jul 15, 2005
  2. =?Utf-8?B?RGFiYmxlcg==?=

    bridview doesn't appear if table is emtpy

    =?Utf-8?B?RGFiYmxlcg==?=, Mar 19, 2006, in forum: ASP .Net
    Replies:
    2
    Views:
    947
    =?Utf-8?B?RGFiYmxlcg==?=
    Mar 19, 2006
  3. Christoph Dahlen
    Replies:
    2
    Views:
    588
    Christoph Dahlen
    Sep 9, 2006
  4. js
    Replies:
    2
    Views:
    384
  5. Switch Within A Switch

    , Apr 22, 2006, in forum: Javascript
    Replies:
    7
    Views:
    94
    Lasse Reichstein Nielsen
    Apr 22, 2006
Loading...

Share This Page