in reply to Elegant way to parse an optional prefix with default?

I'm not sure it qualifies as elegant, but it does do it in one line for all the cases I thought of.

Update: I just realised that the regex below is more complex than it need be; this works too.

Update2: Removed redundant |& (from the top version)

    my($sigil, $name) = ('&'.$_) =~ m/^&?([\$\@%&<*])(.*?)>?$/;

#! perl -sw use strict; for (qw/$foo @foo %foo &foo <foo> *foo foo/) { my($sigil, $name) = ('&'.$_) =~ m/^(?:&?([\$\@%&<*]|&))(.*?)>?$/; print "$sigil:$name\n"; } __END__ c:\test>temp $:foo @:foo %:foo &:foo <:foo *:foo &:foo c:\test>

Nah! You're thinking of Simon Templar, originally played (on UKTV) by Roger Moore and later by Ian Ogilvy

Replies are listed 'Best First'.
Re: Re: Elegant way to parse an optional prefix with default?
by John M. Dlugosz (Monsignor) on Nov 08, 2002 at 17:09 UTC
    I don't get it... isn't  ... ( [\$\@%&<*] | & ) ... redundant? Anything in the class or a & (which is already in the class).

      Spot on John. (wishing I could claim it was my deliberate mistake:)

      A left over from an earlier attempt that didn't work, but like the a doctor, it did no harm, so it got left behind.

      Without that and the previous unnecessary complications, it begins to approach a (small) degree of elegance.


      Nah! You're thinking of Simon Templar, originally played (on UKTV) by Roger Moore and later by Ian Ogilvy
        OK, I see what you're up to. You throw a (possibly extra) & on the front, then match an optional extra one. Instead of removing to leave behind, capture as $2 and assign back to the same variable. As a bonus, you're taking the trailing > as well (per other discussions).

        If it's already known to be syntactically legal, that should do the trick. It doesn't generalize to any kind of default prefix if said prefix could be doubled originally. Otherwise, we have:

        def-prefix . string matches def-prefix? (prefix) (remainder)
        That's a good find worth remembering. Thanks.

        —John