0

I am writing a subroutine that prints an array of non redundant elements from another array.

This code is inside my subroutine.

foreach (@old_table) { push(@new_table, $_) unless ($seen{$_}++); }
print "@new_table" . "\n";                           

Then i call my subroutine in a loop inside my main program, for the first iteration it is OK and my new table contains one occurrence of my old table. But after that @new_table keeps elements from past iterations and the print result is false.

I tried emptying @new_table inside my subroutine like this

@new_table = ();
foreach (@old_table) { push(@new_table, $_) unless ($seen{$_}++); }
print "@new_table" . "\n";       

But then my @new_table becomes empty in all iterations except for the first one.

What is the problem with this and how can i fix it ?

2 Answers 2

2

Due to incorrect scoping, you're reusing the @new_table and %seen of previous passes. Create these just before the loop.

my @new_table;
my %seen;
foreach (@old_table) { push(@new_table, $_) unless ($seen{$_}++); }
print "@new_table" . "\n";

This can be simplified to

my %seen;
my @new_table = grep { !$seen{$_}++ } @old_table;
print "@new_table\n";

You can also use

use List::MoreUtils qw( uniq );

my @new_table = uniq(@old_table);
print "@new_table\n";

You are using use strict; use warnings;, right? If not, you should be. Always.

Sign up to request clarification or add additional context in comments.

Comments

1

You can try uniq from List::MoreUtils to remove redundant elements.

my @new_table = uniq(@old_table);

To quote from perldoc

uniq LIST
distinct LIST

Returns a new list by stripping duplicate values in LIST. The order of elements in the returned list is the same as in LIST. In scalar context, returns the number of unique elements in LIST.

           my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4
           my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.