【发布时间】:2019-04-11 23:18:22
【问题描述】:
我正在使用 Perl。
我从一个包含两列的制表符分隔的 txt 文件开始。
cat1 val1
cat1 val2
cat2 val3
cat3 val4
cat1 val5
cat4 val6
我想将第 1 列中的唯一类别推送到一个数组中并创建与这些唯一类别同名的空变量
所以最后我会:
@unique_categories = ("cat1", "cat2", "cat3", "cat4");
$cat1 = '';
$cat2 = '';
$cat3 = '';
$cat4 = '';
这是我尝试过的:
#! /usr/bin/perl
use strict;
use warnings;
open(my $file,'<',"file.txt") || die ("Could not open file $!"); #input file
my $categories = '';
my @categories_unique = '';
while(<$file>){
chomp;
my $line = $_;
my @elements = split ("\t", $line);
$categories = $elements[0]; #everything seems fine until here
push(@categories_unique, $categories) unless grep{$_ eq $categories} @categories_unique; #with this line I want to store the unique values in an array
#here I want to create the empty variables, but don't know how to
}
【问题讨论】:
-
为什么要创建那些空变量?使用这些类别作为哈希的键听起来更合理;有什么理由不这样做?
标签: perl