-2

私はPerlの初心者です。私が理解していないのは次のとおりです。

次のことができるスクリプトを作成するには:

  • ファイル $source の行をカンマ区切りで出力します。
  • フォーマットされた行を出力ファイルに出力します。
  • この出力ファイルをコマンドラインで指定できるようにします。

コード:

my ( $source, $outputSource ) = @ARGV;
open( INPUT, $source ) or die "Unable to open file $source :$!";

質問: コードを書き始めたときに、出力ファイルのテキストをコマンド ラインで指定する方法がわかりません。

4

2 に答える 2

2

代わりに、次のようなシェルのリダイレクト演算子に依存します。

script.pl input.txt > output.txt

次に、これを行う簡単なケースです。

use strict;
use warnings;

while (<ARGV>) {
    s/\n/,/;
    print;
}

その後、複数のファイルをscript.pl input1.txt input2.txt ... > output_all.txt. または、引数を 1 つ指定して、一度に 1 つのファイルを実行します。

于 2011-07-02T12:31:53.170 に答える
0

私があなたの質問を正しく理解したなら、この例が役立つことを願っています。

プログラム:

use warnings;
use strict;

## Check input and output file as arguments in command line.
die "Usage: perl $0 input-file output-file\n" unless @ARGV == 2;
my ( $source, $output_source ) = @ARGV;

## Open both files, one for reading and other for writing.
open my $input, "<", $source or 
        die "Unable to open file $source : $!\n";
open my $output, ">", $output_source or 
        die "Unable to open file $output_source : $!\n";

## Read all file line by line, substitute the end of line with a ',' and print
## to output file.
while ( my $line = <$input> ) {
        $line =~ tr/\n/,/;
        printf $output "%s", $line;
}

close $input;
close $output;

実行:

$ perl script.pl infile outfile
于 2011-07-01T21:54:28.967 に答える