dottornomade has asked for the wisdom of the Perl Monks concerning the following question:

I just can not open some files I received.

When this simple chunk of code is executed
use IO::File; my @data; if (-e $file) { print "\nopen $file\n"; } if (my $fh->open("$file, r")) { print "I'm in\n"; @data = <$fh>; $fh->close; }

something goes wrong. The file is found (message "open filename" is printed, with filename being the correct name of the file), but then I get this error from the I0::File package:

Can't call method "open" on an undefined value

In other words, it's like there is no string assigned to the variable $file!

Replies are listed 'Best First'.
Re: simple to describe I/O problem
by Laurent_R (Canon) on Sep 01, 2014 at 20:38 UTC
    I fail to see the usefulness of such a complicated construct:
    use IO::File; # ... my $fh=IO::File->new; if ($fh->open($file,"<")) { # ...
    when the whole thing can be done in just one single line of code:
    open my $fh, "<", $file or die "Can't open $file $!";
    To me, this is just looking like pointless over-engineering. Or perhaps OO-fashion victim. Or an application of the following principle: why should we make things simple when they can be made more complicated? Just the contrary of the Perl principles stated many times by Larry Wall and others: to make easy jobs easy.

      I believe one of the advantages of using IO::Handle (from which IO::File inherits) is to have a little more control on a per-handle basis, such as being able to do $io_handle->autoflush(1). Other than that I agree.

        Agreed. I am not saying that that the IO::xxx hierarchy is useless, but just that, in the case in point, this seems to be overkill.
Re: simple to describe I/O problem
by Anonymous Monk on Sep 01, 2014 at 19:20 UTC

    See the documentation of IO::File: you need to initialize your $fh like so: my $fh=IO::File->new; before you use it.

Re: simple to describe I/O problem
by Anonymous Monk on Sep 01, 2014 at 19:25 UTC

    In addition to the above, your arguments to open are wrong, see IO::File. Try this instead:

    ... my $fh=IO::File->new; if ($fh->open("$file","<")) { ...
      if ($fh->open("$file","<")) { ... }

      Why does the string  $file have to be interpolated into another string  "$file" before being passed to the open method?

        It doesn't, "$file" was just a remnant of (too) quickly editing the OP's code. (Unless maybe $file is an object with overloaded stringification; but then it'd probably be stringified inside open...)

      Thank you.

      My bad, it was a trivial mistake, it works now :)