Wednesday, January 12, 2011

File Slurping

#!/usr/bin/perl -w
use strict;

my $holdTerminator = $/;
undef $/;
my $buf = <STDIN>;
$/ = $holdTerminator;
my @lines = split /$holdTerminator/, $buf;
$buf = "init";
$buf = join $holdTerminator, @lines;
print $buf;
print "\n";
 
The preceding code works like this:
  • First we store the terminator character, which by default on Linux systems is linefeed -- "\n".
  • Now we undef the line terminator character
  • Now we slurp the entirety of STDIN
  • Now we restore the line terminator character
  • Now we split the string we read using the termator as a border
  • Now we join the array back into a string
  • We print the string
  • Last but not least, we print an extra newline to fix a picket fence condition

No comments: