سؤال

I am trying to write a script in which I should open a file that can be any file.

But I want to pass the name of file from the command prompt or some other way, so that I don't have to edit the script when ever the input file name changes.

Can any one help how can I do that ?

        open (DBC, "test.txt")|| die "cant open dbc $!";
        @dbc =  <DBC>;
        close (DBC);

the file is in the directory where my script is, that's why am not giving any path here

هل كانت مفيدة؟

المحلول

You want to use the ARGV array for getting, say, the first argument:

my $file = $ARGV[0];
open (DBC, $file)|| die "cant open dbc $!";
@dbc =  <DBC>;
close (DBC);

There are a lot of better ways to eventually do this sort of thing, like checking to make sure they passed something first:

if ($#ARGV == -1) {
    die "You need to supply a file name to the command";
}

my $file = $ARGV[0];
open (DBC, $file)|| die "cant open dbc $!";
@dbc =  <DBC>;
close (DBC);

And you can go on from there, eventually learning about the Getopt::Long and similar modules.

نصائح أخرى

Read perlop #I/O Operators for a shortcut method for processing files passed from the command line. To briefly quote from the linked documentation:

The null filehandle <> is special: it can be used to emulate the behavior of sed and awk, and any other Unix filter program that takes a list of filenames, doing the same to each line of input from all of them. Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-", which when opened gives you standard input. The @ARGV array is then processed as a list of filenames.

Basically, you can simplify your script to just the following:

use strict;
use warnings;

die "$0: No filename specified\n" if @ARGV != 1;

while (<>) {
    # Process your file line by line.

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top