[Dub-pm] 'Shortening' code.
Dave Cross
dave at dave.org.uk
Sat Apr 24 08:08:51 CDT 2004
On Sat, Apr 24, 2004 at 12:42:43PM +0100, Fergal Daly wrote:
> On Sat, Apr 24, 2004 at 09:56:20AM +0100, Dave O Connor wrote:
> > I guess I should have mentioned readability, too. While it can't
> > immediately be said that a one-liner is slower (in fact, it's
> > probbaly faster, unless you've used a module just to squash it down
> > from several lines), it can usually be said that it's less readable.
> > For example, the author of the module gives the following example
> > for slurping a file:
> >
> > open my $file_handle, './Scotty' or die "Scotty can't be slurped:\n$!";
> > local $/; # Set input to "slurp" mode.
> > my $big_string = <$file_handle>;
> > close $file_handle;
> >
> > An equivalent (and more readable way is:
> >
> > open(FH,"Scotty") or die "Scotty can't be slurped:\n$!";
> > my $big_string = join('',<FH>);
> > close(FH);
>
> The author gave the first as an example of boilerplate code that's all
> over everyone's Perl scripts. Your version is slightly shorter but
> could be a whack load slower due to having to parse the file into
> lines and then join them all up again. Plus it stomps on the FH
> package variable which may or may not be OK.
>
> my $big_string = io('./Scotty')->slurp;
>
> is far more readable than either of those and would probably be faster
> than the 3-liner and a tiny bit slower than the 4-liner.
>
> Perl is full of boilerplate code and any module that gets rid of it
> without imposing severe penalties is ok by me,
>
> > While this is more 'idiomatic', it's still obvious to someone with a
> > good grounding in perl what is going on here, and it's definitely
> > not worth writing a module for to 'simplify' your code down the the
> > almighty one-liner :)
>
> This is a 1-liner but it's a 1-liner due to abstraction, not due to
> compaction. A 1-liner (well slightly more) by compaction would be
>
> my $big_string =
> do{local($/,*F);open(F, "./Scotty')||die"Scotty can't be slurped\n$!";<F>}
>
> and that definitely is a bad idea,
There's always File::Slurp
http://search.cpan.org/dist/File-Slurp/
Dave...
--
Oh is the way they say the future's meant to feel
Or just twenty thousand people standing in a field?
More information about the Dublin-pm
mailing list