0

I practiced to insert members to array and sort it then print out the member list.

use strict;
use warnings;
use Data::Dumper;

my $fh = \*DATA;


while(my $line = <$fh>) {



        chomp($line);
        $line =~ s/\s+//g;

        push(my @ArrLines, $line);

        my @SortedArr = sort @ArrLines;

        foreach my $val (@SortedArr) {

                print "$val\n";
        }
}

__DATA__
A2B12,A8B15
A3B27
A5B14,A8B15,A5B18

I hope the output as below, but I found it doesn't work.

A2B12
A3B27
A5B14    
A5B18
A8B15

Note: Remained only one of the duplicated item, like A8B15.

Appreciated for your comments and suggestions.

2 Answers 2

2

Sort after reading, don't sort in the middle.

push(my @ArrLines creates a new @ArrLines every time. Declare it outside the loop.

You don't split on comma anywhere, but seem to need to.

The easiest way to deduplicate is to use a hash instead of an array.

So:

use strict;
use warnings;
use Data::Dumper;

my $fh = \*DATA;

my %lines;
while (my $line = <$fh>) {
    chomp($line);
    $lines{$_}++ for split /,/, $line;
}

my @sorted_array = sort keys %lines;
print Dumper \@sorted_array;
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I looked hash up my reference book. and found Hash can be 1. keys and valuse; 2. a barrel of data. I thought my case suit for a barrel of data. At the beginning, I don't want to use hash for I only remembered that hash is a data structure which including both Keys and values. Thank you.
1

There are a couple of problems:

  1. You need to declare my @ArrLines; above the loop that reads lines. Currently it's being redeclared (and thus set to empty) after each line is read.

  2. You need to perform the sorting and output after the loop that reads lines.

Also you're not splitting the input on commas, and judging from your "expected output" you should be. You can use the split() function for this.

Also, you mention that you want duplicate items to appear only once, but you're not doing anything to achieve that. Once the items are sorted, it's sufficent to check whether the current item is the same as the previous one, and only print it if it's not.

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.