Awk-dogg has asked for the wisdom of the Perl Monks concerning the following question:

For example:

A script master.pl can look in one 26 files (A-Z) to open a file handle from. How do I specify this on a command line so that it will open the correct file.

For example, if I wanted it to open a file in the A directory, I could hard-code master: open(FILEHANDLE, "/data/A/file"); If I'm always going to run the same filename, how could I get it to run based on a command line argument A-Z?

Ultimately I want it to run:

./master.pl A # looks for file under /data/A ./master.pl B # looks for file under /data/B
and so on...

Thanks for the help

Edit: chipmunk 2001-07-15

Replies are listed 'Best First'.
Re: The file I want to open must be determined by a command line argument
by HyperZonk (Friar) on Jul 14, 2001 at 07:50 UTC
    @ARGV contains the command line arguments. Thus, make your open statement:

    open(FILEHANDLE, "/data/$ARGV[0]/file");
      Particularly if the filename is determined from the command line, you want to do as perlsyn says and put an error check on the open which specifies all of the following:
      1. What you were doing.
      2. What the filename is.
      3. The contents of $!.
      In this particular case I think it is also probably worthwhile to have a usage check to inform the user if they call the script with an invalid argument. The obvious alternative is to insert a question in the die which asks them if they called it with the argument that they were supposed to.

      There are very few ideas that I consider more important in writing useful code than trying to make your code debuggable when things go wrong...

Re: The file I want to open must be determined by a command line argument
by Thathom (Acolyte) on Jul 15, 2001 at 01:02 UTC
    Hello,
    I hope this helps in some way.
    I do a similar thing with a project I'm working on.
    When a new user signs up I take the first letter of their name and then depending what it is, I open up a specific folder and file. I have files names "ag.dat" "hn.dat" and so on....
    #FIND OUT WHAT THE FIRST LETTER OF USERNAME IS & #SET FILE NAME TO OPEN $_ = $username; if (/^[a-g]/i) { $filename = 'ag';} elsif (/^[h-n]/i) { $filename = 'hn';} elsif (/^[o-u]/i) { $filename = 'ou';} elsif (/^[v-z]/i) { $filename = 'vz';} elsif (/^[0-9]/i) { $filename = '09';} else { $errormsg = 'Cannot open file'; &Printerror;} #SET THE COMPLETE FILE DESTINATION $dirname = "/absoulute/path/$filename.dat"; #OPEN THE FILE open(FILEHANDLE, "$dirname");
    Not sure if I've quite understood what your asking. Let me know.

    ThAtH0M