1

入力ファイルの各行を複数のファイルに分類するツールを作成したいのですが、ファイルハンドラーの命名に問題があるため、先に進むことができません。どうすれば解決できますか?

これが私のプログラムです

ARGV[0] is the input file
ARGV[1] is the number of classes

#!/usr/bin/perl

use POSIX;
use warnings;

# open input file
open(Raw,"<","./$ARGV[0]") or die "Can't open $ARGV[0] \n";

# create a directory class to store class files
system("mkdir","Class");

# create files for store class informations
for($i=1;$i<=$ARGV[1];$i++)
{
    # it seems something wrong in here
    open("Class$i",">","./Class/$i.class") or die "Can't create $i.class \n";
}

# read each line and random decide which class to store
while( eof(Raw) != 1)
{
    $Line = readline(*Raw);
    $Random_num = ceil(rand $ARGV[1]);
    for($k=1;$k<=$ARGV[1];$k++)
    {   
        if($Random_num == $k)
        {
                    # Store to the file
            print "Class$k" $Line;
            last;
        }
    }
}
for($h=1;$h<=$ARGV[1];$h++)
{
    close "Class$h";
}

close Raw;

ありがとう

後で私はビル・ルパートによって提供されたアドバイスを使用します

filehandlerの名前を配列に入れましたが、構文のバグのようですが、修正できません。構文のバグに########のラベルを付けます。構文エラーですが、問題ないようです#### ####

これが私のコードです

#!/usr/bin/perl

use POSIX;
use warnings;
use Data::Dumper;

 # open input file
open(Raw,"<","./$ARGV[0]") or die "Can't open $ARGV[0] \n";

 # create a directory class to store class files
system("mkdir","Class");

# put the name of hilehandler into array
for($i=0;$i<$ARGV[1];$i++)
{
    push(@Name,("Class".$i)); 
}

# create files of classes
for($i=0;$i<=$#Name;$i++)
{
    $I = ($i+1);
    open($Name[$i],">","./Class/$I.class") or die "Can't create $I.class \n";
}

# read each line and random decide which class to store
while( eof(Raw) != 1)
{
    $Line = readline(*Raw);
    $Random_num = ceil(rand $ARGV[1]);
    for($k=0;$k<=$#Name;$k++)
    {   
        if($Random_num == ($k+1))
        {

            print $Name[$k] $Line;  ######## A syntax error but it looks quite OK ########
            last;
        }
    }
}
for($h=0;$h<=$#Name;$h++)
{
    close $Name[$h];
}

close Raw;

ありがとう

4

2 に答える 2

3

関数に関するPerlのドキュメントprintを引用するには:

ハンドルを配列またはハッシュに格納している場合、または一般に、ベアワードハンドルよりも複雑な式を使用している場合、またはプレーンで添字のないスカラー変数を使用して取得する場合は、ファイルハンドル値を返すブロックを使用する必要があります。代わりに、その場合、LISTは省略できません。

print { $files[$i] } "stuff\n";

print { $OK ? STDOUT : STDERR } "stuff\n";

したがって、print $Name[$k] $Line;に変更する必要がありますprint { $Name[$k] } $Line;

于 2013-03-21T04:08:43.297 に答える
0

これはどう:

#! /usr/bin/perl -w
use strict;
use POSIX;

my $input_file = shift;
my $file_count = shift;
my %hash;

open(INPUT, "<$input_file") || die "Can't open file $input_file";

while(my $line = <INPUT>) {
    my $num = ceil(rand($file_count));
    $hash{$num} .= $line
}

foreach my $i (1..$file_count) {
    open(OUTPUT, ">$i.txt") || die "Can't open file $i.txt";
    print OUTPUT $hash{$i};
    close OUTPUT;
}

close INPUT;
于 2013-03-21T04:55:34.147 に答える