http://www.perlmonks.org?node_id=755577


in reply to FILE reading question.(closed filehandle) issue in script

Hi,

why don't you use Perl's own chdir?

How do you know, that the open() was successful. You should always check for success...

Perl provides its own chdir function. There is no need to use backticks and system commands for this.

Every open() (and other calls) should be checked for success, otherwise you don't know wether it worked or not...

#!/bin/perl -w use strict; ## be strict! always! my $logdir = '/opt/app1/osa/ebcp/5_5_4/log'; my $logfile = 'AppOsaEbcp1.log'; # Changing dir to Log dir; use perl! chdir $logdir or die "chdir $logfile failed: $!\n"; # check open for success!! open my $fh, '<', $logfile or die "$logfile: open failed: $!\n"; my $major=0; my $minor=0; my $critical=0; while( <$fh> ) { chomp; if ( /MAJOR/ ) { $major++; } elsif ( /CRITICAL/ ) { $critical++; } elsif ( /MINOR/ ) { $minor++; } } close $fh or die "$logfile: close failed: $!\n"; # no need for printf if you want to print simple strings print "Count of MAJOR = $major, CRITICAL = $critical, MINOR = $minor\n +";

Update

a shorter version:

#!/bin/perl -w use strict; ## be strict! always! my $logdir = '/opt/app1/osa/ebcp/5_5_4/log'; my $logfile = 'AppOsaEbcp1.log'; # Changing dir to Log dir; use perl! chdir $logdir or die "chdir $logfile failed: $!\n"; # check open for success!! open my $fh, '<', $logfile or die "$logfile: open failed: $!\n"; my %count; while( <$fh> ) { if ( /(MAJOR|MINOR|CRITICAL)/ ) { $count{$1}++; } } close $fh or die "$logfile: close failed: $!\n"; # now with a printf() printf( "Count of MAJOR = %d, CRITICAL = %d, MINOR = $%d\n", @count{qw(MAJOR CRITICAL MINOR)} );

Both code examples are untested!

update: fixed variable mismatch ($line vs. $_)

Replies are listed 'Best First'.
Re^2: FILE reading question.(closed filehandle) issue in script
by Bloodnok (Vicar) on Apr 05, 2009 at 21:49 UTC
    ...could be even shorter - use autodie; would remove the requirement for the ... or die ...; statements in 3 places :D

    A user level that continues to overstate my experience :-))
Re^2: FILE reading question.(closed filehandle) issue in script
by ajay.awachar (Acolyte) on Apr 16, 2009 at 23:30 UTC
    Hi

    Thanks for your valuable suggestion.

    It worked perfectly fine for above stated problem.

    Thanks,

    Ajay