[Melbourne-pm] Error checks without packages

Jacinta Richardson jarich at perltraining.com.au
Thu Jul 28 15:27:39 PDT 2011


On 27/07/11 05:30, Tim Hogard wrote:
> I have this bit of code and the disk partition /usr/local/tmp is full:
> 	#!/usr/bin/perl
>
> 	$SIG{PIPE} = sub { die "\nSigPIPE!\n" };
>
> 	open(OUT,">/usr/local/tmp/x$$") or print "cant open $? $!\n";
> 	print "err $?\n";
>
> 	print OUT  "foo $$ \n" or print "cant print out $? $!\n";
>
> 	print "err $?\n";
> 	close OUT or print "cant close $? $!\n";
> 	print "err $?\n";
>
$? doesn't get set during file operations.

Are you targetting a version of Perl that is more than 11 years old?  If not, 
you might prefer to write this like:

Perl 5.6+

#!/usr/bin/perl
use strict;
use warnings;
use IO::Handle;
use autodie;  # (Perl 5.8.0+)

open my $fh, ">", "/usr/local/tmp/x$$";        # Check your errors if you're not 
using autodie

$fh->autoflush();

print {$fh} "...." or die "Failed to print: $!";

close $fh;  # Check error if you're not using autodie



Or Perl 5.14.1+

#!/usr/bin/perl
use v5.14;
use warnings;
use autodie;

open my $fh, ">", "/usr/local/tmp/x$$";        # Check your errors if you're not 
using autodie

$fh->autoflush();
print {$fh} "...." or die "Failed to print: $!";

close $fh;  # Check error if you're not using autodie


> That helps, but it would be best to know as soon as I open the file
> so I can put the entire output in a different file on a different
> partition.  The unix "open" system call reports "no space" only
> when the directory entry can't be extended and has nothing to do
> with how much space is left on the disk.
>

The problem is that Perl is not your operating system, and Perl cannot tell in 
advance how much data you're going to try to write to disk.  If any.  As such, 
it cannot catch this when you open the file.  What if there's 1gb of space 
available.  But you want to only write 100k.  That should be okay, right?  But 
what if you want to write 3gb?  Sure, if the disk is completely full you want to 
know in advance, but if that's the case you have bigger problems....  I imagine 
you'd have to ask your operating system.  Perl's open() is not the right tool here.

> I could rewind but I'm opening for append since there is small
> chance two processes could write the same file at the same time.
>

The better solution is probably locking.  Unless it doesn't matter if multiple 
processes mix their data.

> I can't flush without loading the IO package (which I don't want
> to).
>
The IO::Handle package is harmless.  I'm really not sure why you'd be trying to 
avoid it.

> Does anyone have any other ideas?

Look into asking the operating system how full that partition is, rather than 
trying to repurpose tools that aren't made for it.  Also, look into modernising 
your Perl syntax to reduce future maintenance pain.

     J


More information about the Melbourne-pm mailing list