Phoenix.pm: Three snippets

Svirskas Rob-ERS007 Rob.Svirskas at motorola.com
Thu May 3 19:40:22 CDT 2001


Here's another common way to slurp a file into a string (after the open):

my $filestring = do { local $/; <FILE>; };

...and my favorite (it's a lot faster than explicit looping or join):

sysread FILE,my $filestring,-s FILE;


                                     - Rob

-----Original Message-----
From: Webmaster [mailto:webmaster at azwebs.com]
Sent: Thursday, May 03, 2001 4:31 PM
To: phoenix-pm-list at happyfunball.pm.org
Subject: Phoenix.pm: Three snippets


Well, since we're on our one liner thing I have two.  I won't be able to
make the meeting, but the one liner topic really sounds like one that I'd
like to attend.  I glean a lot from other peoples tricks.

Here's how I read a file into one string, but I think it can be shortened,
if someone knows a trickier trick.

open FILE, $file;
$filestring = join('', (<FILE>));
close FILE;

In list context, <FILE> returns the list of all lines.  Just join'em with a
null string.

==========

Also, a little something I learned recently...

I wanted to extract a HTML table element from a file, and this code was not
working...

my ($table) = $string =~ /(<table.+?table>)/;

I couldn't figure out why.  Until a quick reference to the Camel Book.  I
needed the 's' suffix to treat the $string as a single string regardless of
newline chars ("\n").

my ($table) = $string =~ /(<table.+?table>)/s;

Without the /s suffix, it would only attempt the match on the first line of
$string if string contained multiple lines.
==========

Lastly, I just learned a fileglobbing technique...
I was writing:
opendir(DIR, $dir);
while (readdir(DIR))  {
    next if /\./;  # don't want current dir and parent dir
    &dosomething_with_file
}
closedir(DIR);

But this could be written as simply as:
map { &do_file_or_dir } <$dir/*>;
or
map { &do_dirs_only } grep {-d} <*>;

Stuff inside the <> is interpolated as a double quote, so you don't have to
double quote (unless you want to).

I don't know why (anyone?...) but when file globbing, the '.' and the '..'
do not appear as they do when doing readir(DIR).


Just thought I'd contribute in absentia (and sans harmonica).

Tim




More information about the Phoenix-pm mailing list