perl-将唯一元素推入数组并根据唯一元素创建变量

时间:2019-04-11 13:55:37

标签: perl

我在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
}

2 个答案:

答案 0 :(得分:4)

具有动态创建的名称的变量很危险,请参阅Why it's stupid to `use a variable as a variable name'A More Direct Explanation of the Problem

在Perl中,您可以使用散列既保留唯一值,又保留未知名称的变量。每次迭代整个数组也要快得多。

#! /usr/bin/perl
use strict;
use warnings;

open my $fh, '<', 'file.txt' or "Could not open file $!";
my %categories;

while (my $line = <$fh>) {
    chomp $line;
    my @elements = split /\t/, $line;
    ++$categories{ $elements[0] };
}
my @categories = keys %categories;

现在,%categories哈希值只是该类别存在的次数。例如,$categories{cat1}是3。如果您决定要使用每个类别的值,则只需替换

++$categories{ $elements[0] };

使用

push @{ $categories{ $elements[0] } }, $elements[1];

答案 1 :(得分:-1)

不错的第一次尝试。这就是你需要的

#! /usr/bin/perl
use strict;
use warnings;

open(my $file,'<',"file.txt") || die ("Could not open file $!"); #input file

my %categories_unique = ();
my @categories_unique = ();

while(<$file>){
    chomp;
    my $line = $_;
    my @elements = split ("\t", $line);
    $categories = $elements[0]; #everything seems fine until here
    $categories_unique{$categories} = 1; # Use the fact that keys in a hash are unique
}

@categories_unique = keys %categories_unique;
{
    no strict 'refs'; # allows access to symbol table
    *{$_} = undef() foreach @categories_unique; create a symbol table entry 
}