reasonablekeith has asked for the wisdom of the Perl Monks concerning the following question:
Can you spot it? Yeah, of course you can, but my code was a bit more involved than this ;). To clarify, what happens is as follows. The first 'while' successfully reads the first line of file1. It prints this line, then the slurp returns file2, and its contents are also printed. Unfortunately, because I used the same file handle, the while thinks its at the end of file1 and and skips to the end.#!/usr/bin/perl -w use strict; open (IN, "file1") or die("can't blah blah"); while (<IN>) { print; print slurp(); } sub slurp { my $slurp = do { local $/ = undef; open IN, "file2"; <IN>}; return $slurp; }
Okay fair enough, filehandles appear to be global, my stupid mistake, but my question is this...
Can I avoid ever making this mistake again?
Should I always 'use FileHandle'? Is this a bit over the top, or worth the effort? It would have been nice if I'd been given some warning too. :)
I'd be interested to hear if others have been caught out by this, and what you're doing now to avoid the same.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Filehandles, scope and warnings.
by Perl Mouse (Chaplain) on Nov 22, 2005 at 11:51 UTC | |
|
Re: Filehandles, scope and warnings.
by davorg (Chancellor) on Nov 22, 2005 at 11:52 UTC | |
|
Re: Filehandles, scope and warnings.
by Moron (Curate) on Nov 22, 2005 at 17:24 UTC |