in reply to map a list

use strict; use warnings; my $str = "a,b=c,e=#f"; my @result = map { /(\w+)(=(#?)(\w+))?/; defined $3 && $3 eq '#' ? "$1=>fn($4)" : defined $2 ? "$1=>$4" : "$1=>fn($1)" } split ',', $str; print "@result";

Prints:

a=>fn(a) b=>c e=>fn(f)

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: map a list
by merlyn (Sage) on Mar 12, 2007 at 20:38 UTC

      Argh, I did know better, I just forgot. However that's not a style I'd recommend for practical code in any case - it would be a dog to maintain and is somewhat obscure. Inserting die if ! in front of the regex might suit the OP's purpose.


      DWIM is Perl's answer to Gödel
Re^2: map a list
by evil_otto (Novice) on Mar 12, 2007 at 19:31 UTC
    Ah! While this answer is not ideal (it doesn't preserve the case : action style of the original, which makes it more straightforward to add in another syntax when that becomes necessary), it did provide the insight for achieving wisdom: since I'm already matching the expression with a RE, I can simply use the work already done and avoid re-splitting. So:
    my @result=map { /(\w+)=#(.+)/ ? ($1,fn($2)) : /(\w+)=(.+)/ ? ($1, $2) : ($_, fn($_)) } split(/,/, $str);
    Thanks.

    Still curious about that segfault tho...

      Depending on what the larger problem is, you may be better looking at something like Parse::RecDescent. Even if you stick to manual parsing, using a more explicit coding structure as shown in dragonchild's example would pay off in terms of maintenance.


      DWIM is Perl's answer to Gödel