On 1/13/06, Dave Whipp <[EMAIL PROTECTED]> wrote: > I'm trying to work out if there's a clever perl6 way to write this using > pattern matching: > > for @*ARGV -> "-f", $filename { > $filename .= absolute_filename; > }
There is, but it's a different kind of pattern matching: if @*ARGV ~~ / <,> -f <,> (.*?) <,> / { $0 .= absolute_filename; } Of course, that only works if you're allowed to modify the source through the $# variables. I think you are, but I'm not certain. This is a good example of how silly the current array matching semantics are. You'd get a match for this call, because of "carelessness" in writing the rule. davesprog foo - f file Because elements are implicitly concatenated together. The "correct" way to write the rule is: / <,> - <!,> f <,> (.*?) <,> / Isn't that dumb? Here's what I counterpropose: matching against arrays treats each element of the array as a single character. <()>-assertions make the current character their topic. There is no <,>; it's implicit in the character-element unification. Here's the new regex: / <( $_ eq '-f' )>. (.) / This method makes more sense for a list of tokens, too. We could shuffle around the special assertions to give shorthands for these presumably common constructs: <( ... )>. <( $_ eq ... )>. <( $_ ~~ /.../ )>. The last one is the most important. It allows you to connect regexes on a stream to regexes on an element of the stream. Possible shorthands for those, respectively: <+( ... )> # treating an assertion as a char class <'...'> # hmm, already takes, maybe we could # make a special case because it # doesn't make much sense for # nonstrings </.../> # obvious > Would this actually work, or would it stop at the first elem that > doesn't match ("-f", ::Item)? If by "stop" you mean "die", yes it would stop. > Is there some way to associate alternate codeblocks for different > patterns (i.e. local anonymous MMD)? As Austin points out, that's called "given". I'll also point out that if we have lookahead in "for" (a feature that I think is best reserved for third-party modules): for @*ARGV -> $cur, ?$next is rw { if $cur eq '-f' { $next .= absolute_filename; } } Which isn't as slick as a pattern matching approach, but it gets the job done without having to use indices. Luke