Lyle Kopnicky wrote:

> One issue that arises in designing for clarity in the code is that
> different developers are used to different idioms.  So, what is clear
> and simple to me may seem obtuse to a future maintainer, and
> vice-versa.  Many of the practices in the Best Practices book seem
> strange to many Perl developers, but Conway suggests that if we would
> all get used to them, we'd be happier in the long run.  It is in that
> spirit that I prefer the three-line map solution to the while loop:
> 
> my @lines = <$infile>;
> map { s/$oldval/$newval/g; $_ } @lines;
> print {$outfile} @lines;
> 
> It conceptually separates I/O from computations.  It is also more
> declarative - saying what you want rather than how to do it.  Some
> programmers may find it less familiar than while loops, but I think that
> is only because they have been taught to use while loops.  If you start
> a new programmer from scratch, my bet is they'll find the map solution
> conceptually simpler.  Granted, I have a functional programming
> background, so I'm apt to say such things.

It might actually run a tad faster too.  :)

> Anyway, despite the fact that the map solution is simpler than the while
> loop, there is yet a simpler solution to this problem, which I mentioned
> earlier.  It involves sucking in the entire file and doing substitutions
> on it.  There is no need to impose the conceptual framework of
> line-based processing.  It might even be faster.  I'm eager to find out.
> 
> Here is the variant I suggest you test:
> 
> use File::Slurp;
> ...
> my $text = read_file($input_file, binmode => ':raw');
> $text =~ s/$oldval/$newval/g;
> print {$outfile} $text;
> 
> (I know Conway suggests using Perl6::Slurp, but I couldn't find a PPM
> for it, so I used File::Slurp.  Admittedly, the binmode => ':raw' is a
> bit obtuse, and could be left out.  I do think it will boost performance
> slightly, which I am curious about in the context of this discussion.)

You could just as easily undef $/ locally and save the need for the module.
But I think you'll find the code to be *considerably* slower than the map
version.  Also, you need the /s qualifier on the s/// in addition to the
/g qualifier.

        my $line; { local $/ = undef; $line = <$infile>; }
        $line =~ s/$oldval/$newval/gs;

_______________________________________________
Perl-Win32-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to