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
In reply to Re^2: Not A Rockstar File Manipulator Today
by TGI
in thread Not A Rockstar File Manipulator Today
by koolgirl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |