Perl使用函数和参数找到在特定文件的每个数组中出现一次的元素

时间:2017-09-22 01:48:54

标签: arrays perl hash

大家早上好, 我想找到一个在特定文件的每个数组中出现一次的元素 所以在每行中它包含bbb \ bbb \ ddd所以输出将是bbb在它的哪一行。 我在每行的每个数组上创建了一个函数,并执行散列以打印在数组中出现一次的元素。 我也想将参数传递给函数。参数是一行中的数组。我发现了类似的话题 Perl find the elements that appears once in an array get the value which is not the same from the row which has duplicate in perl

我的代码

perl.pl

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

open (my $fh, "<content.txt") or die "Could Not Open the file content.txt\n";
while (my @array = <$fh>)
{
        getOnceData(@array);
}
function getOnceData
{
        chomp;
        my (@array) = @_; this is an argument
        @array = split /\\/; #split the \ and pour all the content into the array
        my %count;
        $count{$_}++ for @array;
        print {$count{$_} == 1} keys %count;

}
1;

content.txt

aaa\bbb\aaa
cccd\ade\ade
ppp\www\ppp
www\aaa\www\aaa

我有很多错误......错误说

syntax error at getoncedata.pl line 13, near "my "
Global symbol "@array" requires explicit package name at getoncedata.pl line 13.
Global symbol "@array" requires explicit package name at getoncedata.pl line 14.
Global symbol "@array" requires explicit package name at getoncedata.pl line 16.
syntax error at getoncedata.pl line 18, near "}"

我研究了全局符号的错误,他们说我用这个错误。 我确实把#34;我的&#34;对于全球符号@array

背景资料: 创建一个函数来检查每行上出现一次元素的每个数组。 我创建了一个代码来打开文件,在每行中我将该行作为参数访问并调用函数

1 个答案:

答案 0 :(得分:0)

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

open (my $fh, "<", "content.txt")
   or die("Can't open file \"content.txt\": $!\n");

while (my $line = <$fh>)  # Read the file line by line
{
        chomp $line;  # Remove trailing newline char
        getOnceData($line);  # Pass each lines to getOnceData
}

# Perl has no syntax called `function`
# What you need is `sub`
sub getOnceData
{
        my $line = shift;
        my @array = split /\\/, $line; #split the \ and pour all the content into the array
        my %count;
        $count{$_}++ for @array;
        print grep {$count{$_} == 1} keys %count;  # Don't forget to grep
        print "\n";  # Add newline char

}