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

#!/Users/metaperl/install/bin/perl use strict; my $file = shift or die 'must supply file'; my ($white,$black) = split '-', $file; my $color; if ($white =~ /princepawn/) { $color = 'w'; } else { $color = 'b'; } my @cmd = ('annotateh', $file, $color, qw(1-999 1 5)); warn "@cmd"; system @cmd;

Replies are listed 'Best First'.
Re: How would you shorten this regexp conditional?
by japhy (Canon) on Jan 25, 2002 at 17:23 UTC
    I'd just use the ternary operator: my $color = $white =~ /princepawn/ ? 'w' : 'b'; If I was feeling rowdy, I might do: my $color = ('b','w')[$white =~ /princepawn/];

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      my $color = ('b','w')[$white =~ /princepawn/];
      Beware.. I've been burned by code like that. In a list context (which the indicies of a suffix part is eval'ed in), that's an empty list return for false, not "0", so you end up with an empty list value, and $color is undef, not the first item! You need a scalar inside the brackets to get it right, as in:
      my $color = ('b','w')[scalar $white =~ /princepawn/];

      -- Randal L. Schwartz, Perl hacker

        Except that this is in scalar context because of the scalar assignment. Had I mistakenly written my($color) = ..., then I agree I would have been burned, and rightly so.

        _____________________________________________________
        Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
        s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: How would you shorten this regexp conditional?
by petral (Curate) on Jan 25, 2002 at 23:32 UTC
    This isn't golfing.   But seriously, I see no reason for the intermediates (or the logic in their names).
    my $color = $file =~ /^[^-]*princepawn.*?-/ ? 'w' : 'b';
    (Depending on the range of possible locations of "princepawn" in the input, the regex could be simpler.)

    But since others with far deeper understanding have not suggested it, I must be missing something.

      p