I have a subroutine that takes a filehandle as an argument. How do I make a filehandle from a file path specified on the command line? I don’t want to do any processing of this file myself, I just want to pass it off to this other subroutine, which returns an array of hashes with all the parsed data from the file.
Here’s what the command line input I’m using looks like:
$ ./getfile.pl /path/to/some/file.csv
Here’s what the beginning of the subroutine I’m calling looks like:
sub parse { my $handle = shift; my @data = <$handle>; while (my $line = shift(@data)) { # do stuff } }
Command line arguments are available in the predefined
@ARGVarray. You can get the file name from there and useopento open a filehandle to it. Assuming that you want read-only access to the file, you would do it this way:Note that the
or die...checks the callopenfor success and dies with an error message if it wasn’t. The built-in variable$!will contain the (OS dependent) error message on failure that tells you why the call wasn’t successful. e.g. ‘Permission denied.’