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

un-Nifty qr OR ASCII bullet parser

by belg4mit (Prior)
on Aug 13, 2009 at 19:04 UTC ( #788420=snippet: print w/replies, xml ) Need Help??
Description: While searching for a parse of ASCII bulleted lists the other day, I ended up rolling my own:

while( $text =~ /\G\s*($bullet)\s*([^\n]+)((?:\s*$bullet{2,}\s*[^\n]+)+)?/g ){ ...}

And stumbled across what I believed to be a clever use of qr to create $bullet from a separate data structure (which permits us to later determine what style of bullet we had, and map it to something):
%bullets = ('*'=>'foo', '+'=>'bar', '@'=>'qux');

#Original, which as ikegami points out, doesn't quite work
#my $bullet= sprintf(qr/[%s]/, join('', keys %bullets));
#Alternate form, that I was trying to make more scrutable, with added 
my $bullet=  qr/[\Q@{[join '', keys %bullets]}\E]/;
Replies are listed 'Best First'.
Re: Nifty qr OR bullets with butterfly wings
by ikegami (Pope) on Aug 13, 2009 at 19:24 UTC
    Safer (allows "-", for example):
    my $bullet = sprintf qr/[%s]/, quotemeta join '', keys %bullets;
    Alternative (shorter and returns a compiled regexp unlike the OP's and the above solutions):
    my ($bullet) = map qr/[\Q$_\E]/, join '', keys %bullets;
      Alternative (shorter and returns a compiled regexp unlike the OP's and the above solutions):
      Huh? My code returns (?-xism:[@*+]), but the inclusion of \Q is a good idea.

      In Bob We Trust, All Others Bring Data.

        It returns the string (?-xism:[@*+])

        1. qr/[%s]/ builds a regex that matches strings containing "%" or "s".
        2. sprintf stringifies the compiled regex to (?-xism:[%s]) to use it as the format pattern.
        3. The characters are included into the format pattern and the result is returned by sprintf.

        So not only do you not end up with a compiled pattern, you waste time compiling a pattern you never use!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://788420]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2017-06-27 03:13 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (598 votes). Check out past polls.