Phoenix.pm: Three snippets
Jo Brooks
jobrooks at us.dhl.com
Thu May 3 20:11:43 CDT 2001
i also won't be able to make it, but i found this utility a couple
years ago, and it's nearly indispensible:
# Usage: dos2unix dosfile ...
print STDERR "Converting \"$ARGV\" ...\n" if (eof || ($. == 0));
s/\015$//; # strip ^M from end of line.
s/\032$//; # strip ^Z if we see it (which'll be at EOF).
one of the best things i've ever found on the 'net :)
jojo
Svirskas Rob-ERS007 wrote:
>
> 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