in reply to Re: Not A Rockstar File Manipulator Today
in thread Not A Rockstar File Manipulator Today
The good:
The bad:
use strict; use warnings; my %settings; foreach my $key (qw(input output pattern replacement)) { print "$key = "; my $setting = <STDIN>; chomp $setting; $settings{$key}=$setting; } open IN, '<', $settings{input} or die "Can't open input file $settings{input}: $!"; die "Output file $settings{output} already exists\n" if -e $settings{output}; open OUT, '>', $settings{output} or die "Can't open output file $settings{output}: $!"; while (<IN>) { s/$settings{pattern}/$settings{replacement}/g; print OUT $_; } close (IN); close (OUT);
Now, there are still some problems with this code. The big one is that using a hash and keys for storing the settings, looses us the benefits of using strictures in the first place. If I misspell 'output' when I use it, I'll get no warnings. Perl happily autovivifies a value in the hash and returns an undef.
There are ways around this issue. The easiest is to use Hash::Util to lock the hash, so that attempts to change the hash or access nonexistent keys become a fatal error.
use Hash::Util qw(lock_hash); my %settings; foreach my $key (qw(input output pattern replacement)) { print "$key = "; my $setting = <STDIN>; chomp $setting; $settings{$key}=$setting; } lock_hash %settings;
Another thing is the use of global file handles. I should really be using lexical filehandles. Global handles are global variables, with all the attendant problems.
TGI says moo
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Not A Rockstar File Manipulator Today
by ptoulis (Scribe) on Nov 16, 2008 at 00:03 UTC | |
by TGI (Parson) on Nov 16, 2008 at 08:54 UTC | |
by ptoulis (Scribe) on Nov 16, 2008 at 15:50 UTC | |
by TGI (Parson) on Nov 16, 2008 at 19:37 UTC | |
by ptoulis (Scribe) on Nov 16, 2008 at 23:21 UTC |