0

ユーザーにファイル名を尋ねることから始まるスクリプトがあります。プログラムを実行する前でも、コマンドラインでファイル名を指定できる機能を追加したいと考えています。

要点: "perl wordcounter.pl text.txt" でプログラムを開始した場合、プログラム名の後の文字列 (つまり、text.txt) にコード内からアクセスするにはどうすればよいでしょうか?

私は次のようなことを始めました:

$filename = "Filename supplied in the commandline";
if ($filename == 0) {
    print "Word frequancy counter.\nEnter the name of the file that you wish to analyze.\n";
    chomp ($filename = <STDIN>); 
}

基本的に、コマンドラインでテキストファイルが指定されていない場合、$filename は 0 のままで、ファイルの要求に進みます。

コード内の「コマンドラインで指定されたファイル名」にアクセスする方法を知っている人はいますか?

4

2 に答える 2

1

@ARGV は有望なオプションですが、getopts を使用したいのですが、必要に応じて使用できるサンプル コードを次に示します。

このperl sample.pl -file text.txt を試して、ファイル引数perl sample.plなしでもう一度試してください

#!/usr/bin/perl
use Getopt::Long;

# setup my defaults

GetOptions(
    'file=s'    => \$file,
    'help!'     => \$help,
) or die "Incorrect usage!\n";

if( $help ) {
    print "Common on, it's really not that hard.\n";
} else {
    print "reading the $name.\n";
    if ( -e $file ){
        open( DATA ,'<',$file ) or die "unable to open \$file = $file\n";
        while (<DATA>){
            print "$_\n";
        }
    } else {
        chomp ($file = <STDIN>);
        open( DATA ,'<',$file ) or die "unable to open \$file = $file\n";
        while (<DATA>){
            print "$_\n";
        }

    }
}
~
于 2013-10-31T11:14:51.710 に答える