Stupid Perl Trick
Where I work we have to processes files from many sources, we have found three different line endings: “\n”, “\r\n”, and “\r”. We didn’t want to process all the files before, er, processing them so I wrote the following:
#!/usr/bin/perl
use warnings;
use strict;until (($/ = getc(STDIN)) =~ m/[\r\n]/) {
die “no new line!” if (eof(STDIN));
};
if ($/ eq “\r”) {
$/ .= “\n” if (getc(STDIN) eq “\n”);
}
seek(STDIN,0,0); # rewind()
This will set $/ to which ever of the three file endings we have so you can then process them without thinking. Well, almost no thinking, you will need to use chomp instead of chop. I’m sure it could be nicely abstracted too, bit I didn’t.
Comments Off on Stupid Perl Trick