|Welcome to the Monastery|
Re^3: Looking for ideas on how to optimize this specialized grepby furry_marmot (Pilgrim)
|on Jan 25, 2011 at 02:12 UTC||Need Help??|
So you think setting $/ = "\n\n" and ($headers) = <$fh> should be faster?
It's $/ = '', not $/ = "\n\n". It's just the way it works. And setting it to $/ = undef will slurp in the whole file. Anyway, yes, I think one file read and one match will be a lot faster than a dozen or so reads and a dozen or so matches, depending on the particular header.
Then regex against $headers and anchor against specific headers. But, many addresses are "hidden" in the first received header because of mailing lists or other things, because of that I had looked at the entire header. Maybe /(?:^To:\s+|^CC:\s+|<)$address/ms?
Well, you have to adjust the regex to your needs, but as I said, it's one match that covers all the places the address could be...including the whole header block, if necessary, versus a bunch of reads and matches.
I generally use /xms on all my regexes as that is how I expect them to work, and if I add them, it doesn't hurt even if I don't use the feature. Is there a reason NOT to use /x and /s? Do they slow down the regex?
My feeling is that setting features you don't use as defaults is a bad practice. Programming is very much a thinking endeavor. Always setting /xms and can lead to some very nasty bugs when you forget what those options actually mean or that you have set them. For example, '+' is greedy. Once you have a basic match, like m/Start.+finish/s for example, this regex will search all the way to the end of the block of text and start working backwards to find 'finish'. Without the /s modifier, it only searches to the next newline to start working backwards.
Similarly, /m just lets you match ^ and $ against embedded newlines. If you forget and search for m/^Something/m, you might get unexpected results. They are just tools. You can write code that always accommodates the use of those modifiers, but why? It's like deciding that you will always use a screwdriver, even when you don't need it. It's odd...Anyway, I stripped the code to its basics and benchmarked it. The one read/one match approach is about 30% faster than your approach, so there ya go. Also, I copied sub1 and sub3 as sub2 and sub4, and then changed the regex to use or not use /xms. Turns out sub4 runs about 2% more slowly than sub3, probably because the particular regex does a lot of backtracking. sub2, where I removed the /xms, runs about 10% more slowly! I've run it a few times, and it's consistent. I didn't expect that and don't understand it.