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

die "cant find key\n" unless ($text->as_string() =~ /KEY=([^&]+)\&/); my $key = $1;
what is this code doing. i dont understand what the regex part should match with
thanks.

Replies are listed 'Best First'.
(jeffa) Re: A regex I cant get my head around
by jeffa (Bishop) on Aug 03, 2002 at 20:56 UTC
    Looks like it is trying to parse key value pairs that are delimited by ampersands ... maybe GET parameters? [^&]+ matches anything that is not an ampersand and the parens around it capture the match into $1. \& matches a mandatory ampersand. Here is some test code to see what is matched and what is not:
    use strict; for (qw(foo foo& &foo foo&bar)) { /([^&]+)\&/; print "$_ - $1\n"; }
    Seems to me that the variable $key in your code should be renamed $value, because that is what it is really trying to capture. Also, depending upon what the goal really is for this code, i might suggest using a CPAN module such as URI to pull out the key/value pairs:
    use strict; use URI; my $uri = URI->new(); $uri->query('THING=super%20hero&KEY=foobar'); my %hash = $uri->query_form(); print $hash{KEY}, "\n";
    Notice that KEY is last, and it's value is not succeeded by an ampersand.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      Thanks cLive and jeffa, but it has nothing to do with GET params. If
      $text->as_string() = "startKEY=jdjhjfg8y4uh449845&finish"
      what value ids assigned to $key?
        Why not find out for yourself? All you need to do is change your code to something like:
        my $as_string = 'startKEY=jdjhjfg8y4uh449845&finish'; $as_string =~ /KEY=([^&]+)\&/; print $1, "\n";
        Regardless of whether or not this has to do with GET params, you can still use URI to parse any key=value pairs that are delimited by ampersands:
        use strict; use URI; my $uri = URI->new(); $uri->query('startKEY=jdjhjfg8y4uh449845&finish'); my %pair = $uri->query_form(); print $pair{startKEY}, "\n";

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        B--B--B--B--B--B--B--B--
        H---H---H---H---H---H---
        (the triplet paradiddle with high-hat)
        
Re: A regex I cant get my head around
by cLive ;-) (Prior) on Aug 03, 2002 at 20:47 UTC
    "KEY=", followed by one or more (greedy) not &s, followed by an &

    cLive ;-)

    --
    seek(JOB,$$LA,0);

      so if
      $text->as_string() = "startKEY=jdjhjfg8y4uh449845&finish"
      what value ids assigned to $key?
        $text->as_string() = "startKEY=jdjhjfg8y4uh449845&finish"

        what value ids assigned to $key?
        jdjhjfg8y4uh449845
        -sauoq
        "My two cents aren't worth a dime.";
        
        jdjhjfg8y4uh449845