David Gilden wrote:
Greetings,

I was looking for a way to improve the following:

#  Check to make sure it is an inTune File
open (FH, UPLOAD_DIR . "/$file")  || error( $q, "Error reading $file for test :  
$!" );

while(<FH>){
if ($_ !~ /\*{5} InTune/){
unlink( UPLOAD_DIR . "/$file") or error( $q, "Problem deleting file $!");
error( $q, "The file you uploaded is not an inTune file. Only an inTune export file will be accepted." ); }
last;
} close FH;


It never seemed to work consistently. So after reading through my Perl archive here is what I am now using, which works great! ( special thanks to, Randal L. Schwartz )


# Check to make sure it is an inTune File open (FH, UPLOAD_DIR . "/$file") || error( $q, "Error reading $file for test : $!" );


while (($_ = <FH>) !~ /[*]{5} InTune/) {
unlink( UPLOAD_DIR . "/$file") or error( $q, "Problem deleting file $!");
error( $q, "The file you uploaded is not an inTune file. Only an inTune export file will be accepted." );
last;
} close FH;

The above is wrong. It is not cross-platform safe. Some OS do not allow you to unlink an open file. Always explicitly close files.


use File::Spec;
my $path = File::Spec->catfile( UPLOAD_DIR, $file );

open( my $fh, $path ) or die $!;

my $found_something_objectionable = 0;
while (defined( my $line = <$fh> )) {
  if ( $line !~ /something/ ) {
    ++$found_something_objectionable;
    last;
  }
}

close( $fh );

if ( $found_something_objectionable ) {
  unlink( $path ) or error(...);
  error(..);
}


If you only care about the first line, then don't use a loop. Replace it with something like:


my $line = <$fh>;
++$found_something_objectionable if $line =~ /something/;

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




Reply via email to