How to get a file descriptor from the command line?

I have a routine that takes a file descriptor as an argument. How to create a file descriptor from the file path specified on the command line? I don’t want to process this file myself, I just want to transfer it to this other routine, which returns an array of hashes with all the analyzed data from the file.

Here, what uses the command line input is as follows:

$ ./getfile.pl /path/to/some/file.csv

Here, what the start of the subroutine that I call looks like this:

sub parse {
    my $handle = shift;
    my @data   = <$handle>;
    while (my $line = shift(@data)) {
      # do stuff
    }
}
+3
source share
4 answers

@ARGV. open . , , :

my $file = shift @ARGV;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
parse($fh);

, or die... open , . $! ( ) , , . " ".

+16

parse(*ARGV) - : , Perl Perl.

(<>), ARGV, : , @ARGV, STDIN, @ARGV .

perldoc perlop:

<> : sed awk. <> , . : <> @ARGV, , $ARGV[0] "-", . @ARGV .

while (<>) {
    ...                     # code for each line
}

Perl- :

unshift(@ARGV, '-') unless @ARGV;
while ($ARGV = shift) {
    open(ARGV, $ARGV);
    while (<ARGV>) {
        ...         # code for each line
    }
}

, , . @ARGV $ARGV. filehandle ARGV - <> - <ARGV>, . ( <ARGV> .)

<> while - my $data = <> , my @data = <>; , *ARGV, .

+5

-n !

:

#!/usr/bin/perl -n

#do stuff

$_. ,

./getfile.pl/path/to.csv

.

See here and here for more information about this. I like -p too, and found the combos -a and -F really useful.

In addition, if you want to do additional processing, add BEGIN and end blocks.

#!/usr/bin/perl -n

BEGIN {
  my $accumulator;
}

# do stuff

END {
  print process_total($accumulator);
}

or whatever. This is very, very helpful.

+1
source

Am I missing something or are you just looking for an open () call?

open($fh, "<$ARGV[0]") or die "couldn't open $ARGV[0]: $!";
do_something_with_fh($fh);
close($fh);
-1
source

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


All Articles