« Square-Wheeled Bicycle | Main | Origin of the Phrase "Proudly Serving My Corporate Masters" »

July 26, 2005

switch -file, and Regex Hooha

Here's another cool thing in Monad. You know in Perl you have the <> syntax for ripping through files: you get code sequences like:

open FH,"filename";
while (<FH>)
    if (some-regular-expression) {
        # code to handle lines that match
    }
    elsif (another-regular-expression) {
        # code to handle lines that match
    }
    # etc.
}
close FH;

Well, Monad has a -file option on the switch statement which can do similar things, especially when combined with the -regex option on switch (which tells it to do regex instead of exact matching):

switch -file "filename" -regex {
    "some-regular-expression" {
        # code to handle lines that match
    }
    "another-regular-expression" {
        # code to handle lines that match
    }
    # etc.
}

If you want to run through a bunch of files, then you can enclose the switch in a foreach. Also, in a switch statement $_ is the matched object. So putting this all together you get a basic grep (looking for the word "FileInfo" in all *.mshxml files) that looks like:

foreach ($f in resolve-path *.mshxml) { switch -file $f -regex { "FileInfo" { ($f.Path + ": " + $_ ) } } }

Finally, .Net has capture groups, like Perl, as discussed here; the groups wind up in the Monad variable $matches, so $matches[0] is the text matched by the whole regex, automatically numbered captures wind up in $matches[1], $matches[2], etc., and named captures (specified via (?<name>regex) in .Net) wind up in $matches["name"] ($matches is a hashtable, so $matches.name also works). Viz:

switch -file c:\boot.ini -regex { "(?<arcname>.*)=`"(?<displayname>.*)`"" { ("NAME " + $matches.displayname); ("ARC " + $matches.arcname) } }

The regular expression is:

"(?<arcname>.*)=`"(?<displayname>.*)`"

(Trust me, wade through it and you'll learn something.) That is put everything up to the first equal sign in a capture called arcname, then put everything between the double quotes in a capture called displayname (recall that the backtick ` is the Monad escape character, it escapes the double quotes here).

UPDATE: Lee Holmes had a blog entry about Monad regular expressions. In fact, it was an internal email about his entry, pointing out the switch -file syntax, that inspired this one.

Posted by AdamBa at July 26, 2005 11:30 AM

Trackback Pings

TrackBack URL for this entry:
http://proudlyserving.com/cgi-bin/mt-tb.cgi/272

Comments