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;

谢谢

后来我使用了比尔鲁珀特提供的建议

我将文件处理程序的名称放入数组中,但它似乎出现了语法错误,但我无法纠正它我用########标记语法错误,语法错误,但看起来还不错#### ####

这是我的代码

#!/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 回答