Skip navigation.

Harold's Home

   Home
  
XML version of this site

PHP Scripts

Index
CLI fun
Mail on 404
HB-NS (NewsScript)

Downloads

Applescripts
APOD to Desktop
Dreamweaver Extensions

Stuff

Writings
Other stuff
Central Grinder

OOOk Default:

VJ stuff
VJ Tools
Bananas
Strippers
Sample Movies

News

The Inspiration Particle
I was struck by an inspiration particle this morning.
These particles are extremely rare and hardly interact with normal matter, much like the much more common neutrino. Luckily while in the shower this morning one hit a neuron and I figured out how to read a whole file into a string (using Perl).

Most examples of file manipulation, in books and on the web, iterate through a file one line at a time, which is fine as far as it goes, but if your problem requires you to look at certain conditions in the entire file you're shit out of luck.

Here's how to read an entire file into a string:
open (DATA, "< $filename") or die "Can't read $filename";
my $whole_file = "";
while (<DATA>)
{
    $whole_file .= $_;# concatenate file into one string
}
close (DATA);


Now we can do all kinds of manipulations on the entire string, like using regular expression substitutions:
$whole_file =~ s/match pattern/replace pattern/g;.

Besides being quite elegant, in my case this actually speeded up my code by half a second. Instead of 0.6 seconds the script now only takes 0.1 second to run. As this script will run on about 50 files a month when deployed this means I just saved my employer 25 seconds computing time a month. I doubt I will get an additional christmas bonus though. My colleagues all shrugged when I came in this morning and tried to share my joy.
Still: Joy!

Here's how to time a script by the way (shamelessly ripped from the seminal Mastering Regular Expressions):
#!/usr/bin/perl -w
use Time::HiRes 'time';
my $start = time;

# your code goes here

my $delta = time - $start;
printf "$0 took %.5f secondsn", $delta;

Show all items | Read all items

About, copyright, privacy and accessibility | Mail