Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^3: Regex KungFu help needed

by AnomalousMonk (Archbishop)
on Oct 02, 2009 at 22:59 UTC ( [id://798952]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Regex KungFu help needed
in thread Regex KungFu help needed

As a further step, associating patterns with their counts and (cached) regex objects in a hash may be worthwhile:
>perl -wMstrict -le "my $sequence = 'GGGGGGGAGAAAAAAAAAAAAAAAGAAGGA'; my %patterns = map { $_ => { count => 0, regex => qr{ (?= \Q$_\E) }xms } } qw(AAAAA GGGGG GGAGA GAAGG) ; $patterns{$_}{count} =()= $sequence =~ m{ $patterns{$_}{regex} }xmsg for keys %patterns; print qq{$_: $patterns{$_}{count}} for sort keys %patterns; " AAAAA: 11 GAAGG: 1 GGAGA: 1 GGGGG: 3
or
>perl -wMstrict -le "my $sequence = 'GGGGGGGAGAAAAAAAAAAAAAAAGAAGGA'; my %patterns = map { $_ => { count => 0, regex => qr{ (?= \Q$_\E) }xms } } qw(AAAAA GGGGG GGAGA GAAGG) ; $_->{count} =()= $sequence =~ m{ $_->{regex} }xmsg for values %patterns; print qq{$_: $patterns{$_}{count}} for sort keys %patterns; " AAAAA: 11 GAAGG: 1 GGAGA: 1 GGGGG: 3

Replies are listed 'Best First'.
Re^4: Regex KungFu help needed
by johngg (Canon) on Oct 03, 2009 at 11:03 UTC

    Nice, ++

    If you don't need to refer to the pattern again you can reduce that to a single step with the uncompiled pattern as key and count as value.

    $ perl -Mstrict -wle ' > my $seq = q{GGGGGGGAGAAAAAAAAAAAAAAAGAAGGA}; > my %pats = map { > $_, scalar( () = $seq =~ m{(?=\Q$_\E)}g ); > } qw{ AAAAA GGGGG GGAGA GAAGG }; > print qq{$_: $pats{ $_ }} for sort keys %pats;' AAAAA: 11 GAAGG: 1 GGAGA: 1 GGGGG: 3 $

    I expect some Monks could golf that down to seven bytes and a nybble :-)

    Cheers,

    JohnGG

    Update: Extra parentheses inside the map were un-necessary, removed!

      As you wish :)

      print "$_: ", $t = () = GGGGGGGAGAAAAAAAAAAAAAAAGAAGGA =~ /(?=\Q$_\E)/ +g, $/ for AAAAA,GAAGG,GGAGA,GGGGG

      Removing whitespaces is left as an exercise for the reader :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://798952]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2024-04-19 07:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found