Perl open file error handling

I want to perform some task when the file does not open in the Perl program below. But when I run it, I get syntax errors. What is wrong with him?

my $LOGPATH = $ENV{DATA_OU};
my $LOGFILE =  "cdj_rep" . "." . "test" . ".rpt";

if ! (open(OUT,">$LOGPATH/test1/work/$LOGFILE")) {
   print "testin";
   return;  
}

close(OUT);
+3
source share
2 answers

The! it is necessary to go in brackets:

if (! open (out,
+9
source

I would write it as

my $LOGPATH = $ENV{DATA_OU};
my $LOGFILE = "cdj_rep.test.rpt";
my $path    = "$LOGPATH/test1/work/$LOGFILE";

open my $fh, ">", $path or do {
  warn "$0: open $path: $!";
  return;
};

close $fh or warn "$0: close $path: $!";

Put all the way in $pathso that you don’t have to repeat it several times, and if you ever need to change it, you can do it in one place.

open (my $fh), . , $fh .

3- open, , . , .

open

open my $fh, "<", $path
  or die "$0: open $path: $!";

if (!open ... unless (open ... , . , , open or ... , . , , , do { ... }, .

, warn:

  • ($0)
  • , (open $path)
  • ($!)

warn die , .

, close , , , , , , -.

+11

Source: https://habr.com/ru/post/1754330/


All Articles