On 4/18/07, yitzle <[EMAIL PROTECTED]> wrote:
Any tips on compacting this sub?

sub readFile($) {
        my $fileName = shift;
        open FILE, "<", $fileName;
        while (<FILE>) {
                my($name,$oldCount,$oldNum) = split /~/;
                $dHash{$name}{'oldCount'} = $oldCount;
                $dHash{$name}{'oldNum'} = $oldNum;
        }
        close FILE;
}

Don't use prototypes.  They are broken and will give you a false sense
of security.

Don't use global variables (%dHash), they make your code harder to
read and maintain.  Read up on decoupling.

Use lexical file handles instead and you don't have to close it (they
auto-close when they go out of scope).

open my $file, "<", $fileName or die "Could not open $fileName: $!";
while (<$file>) {

Use an anonymous hash ref in stead of assigning and use smaller names
for variables with limited scope.

my ($name,$cnt,$num) = split /~/;
$dHash{$name} = { oldCount => $cnt, oldNum => $num };

Alternatively, use a hash slice if you don't want to disturb other
keys that may exist at the level in %dHash

my ($name,$cnt,$num) = split /~/;
@{$dHash{$name}}{qw(oldCount oldNum)} = ($cnt, $num);

Here is my version:
sub readFile {
   croak "readFile expects (filename, hashref)" unless @_ == 2 and
ref $_[1] == 'HASH';
   my ($file, $h) = @_;
   open my $f, "<", $file or die "could not open $f for reading: $!";
   while (<$f>) {
       my ($name, $cnt, $num) = split /~/;
       @{$h->{$name}}{qw(oldCount oldNum)} = ($cnt, $num);
   }
}

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to