1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your suggestion i'll go through Getopt::Long once again thank you for help
You're welcome. If you're new here, you should accept the best answer you get and upvote ones that help you. Otherwise you'll get a poor reputation and people will stop answering your questions :-)
You bet. Welcome to the stack overflow party!
0

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. } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.