in reply to finding unique items in an array, from a text file

If this is homework, you should probably tell us. People don't mind helping, but we don't want to do your homework for you.

I'm assuming this isn't homework, then. You're over thinking things, for one. Simplify it. There's no need to build an array of lines just to build a hash of lines, for example.

Beyond over thinking the problem, you have some specific issues with your code:

  1. Your version is not even syntactically correct.
  2. You check $item but you never assign anything to it. Either use the default variable ($_) or specify a loop variable.
  3. You say you're wanting to find unique lines, but you are trying to print all lines instead of the unique ones.

use strict; use warnings; # you left this out my $file = "controls.txt"; open (my $fh, '<', $file) or die "Can't open $file for read: $!"; # Don't use two-arg open unless you know why, and use # lexical filehandles unless you know of a reason not to. my %seen; while ( <$fh> ) { $seen{$_} = 1; # Later assignments to an identical key # overwrite earlier ones, so there's really # no need to check if all you want is uniqueness. } my @unique = keys %seen; print @unique;

This could, for a very simplified version, boil down to this:

perl -le '$seen{$_}++ while <>; print keys %seen;'

Under perl 5.10, this is a decent Perl golf version:

perl -lE'$s{$_}++for<>;say keys%s'

Don't play golf with code you intend to use for serious work or for a school project. I did it here just to show you how much you are complicating the task for yourself. There are actually very few things going on in this code on the level at which Perl is capable of processing it for you. The only steps you need are:

  1. read the file line by line, optionally with an explicit open and error check (which if you're using it for serious work would be "less optional")
  2. assign to a data structure that maintains uniqueness of keys (hash)
  3. gather and print the data as limited by the previous step (keys returns all the keys of a hash, and then that gets printed
The for loop makes an extra copy in memory that you don't need. Everything you need to do can be done with a while loop. Some may consider that distinction a premature optimization. It's something to consider, though, if you're working with large files.