I came across this Perl construct today:
@foo = split('\n', $bar);
That works well for splitting a large string into an array of lines for UNIX-type line endings, but leaves a trailing \r for Windows. So I changed it to:
@foo = split('\r?\n', $bar);
Which splits the string by lines and doesn’t leave a trailing \r (tested under ActivePerl 5.8). Then it was pointed out to me that this should probably be:
@foo = split(/\r?\n/, $bar);
So why does the second variant work at all? The double quotes mean that the contents are evaluated, which is why the \r and \n are actually treated as CR and LF, but the ? is treated as a regex metacharacter rather than a literal question mark.
Are the slashes around the regular expression just optional for split()? Is it just assumed that the first parameter to the function will be a regex?
You can pass split a regex as a string or a regex literal. So passing it as a double-quoted string is fine.
You can also delimit regular expression literals with characters other than the standard /regex/