CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
2 questions about a while loop

 



lukdk
Novice

Sep 1, 2014, 7:07 AM

Post #1 of 4 (2170 views)
2 questions about a while loop Can't Post

Hello,

I'm trying to remove the double entries in a alphabeticly ranged list.

This example does the trick for me:


Code
 
use strict;
use warnings;
use lib "d:/perl";
use MOlib;

my @file=MOlib::read_file("input.txt");
my $old=shift @file;
my @result;
push (@result,$old);
foreach my $line (@file){
if ($old ne $line){
push (@result,$line);
$old=$line;
}
}
open (RESULT, ">result.txt") or die "Can't open result.txt: $!\n";
print RESULT @result;
close RESULT;


I tried to make the code smaller by removing unneeded variables and came with this code:




Code
 
#use strict;
use warnings;
use lib "d:/perl";
use MOlib;

my @file=MOlib::read_file("input.txt");
push (my @result,shift @file);
while (<@file>){
if ($result[-1] ne $_){
print "$result[-1] $_\n";
push (@result,"$_\n");
}
}
open (RESULT, ">result.txt") or die "Can't open result.txt: $!\n";
print RESULT @result;
close RESULT;


Why is that code not working? Adding print "$result[-1] $_\n"; to troubleshoot shows me the condition would always be true.

why does this looks like it's actually printing an extra space before each $_? and why do i need to add a \n when i push the variable to the array? Each line of that file should end with a newline and i don't understand how i'm removing it.


(This post was edited by FishMonger on Sep 1, 2014, 7:35 AM)


FishMonger
Veteran / Moderator

Sep 1, 2014, 7:43 AM

Post #2 of 4 (2166 views)
Re: [lukdk] 2 questions about a while loop [In reply to] Can't Post

It would be helpful if you showed us a sample of the contents of input.txt and your read_file() sub.

If you want to remove duplicates, you should use a hash. An example doing this is a perl FAQ.

C:\>perldoc -q "How can I remove duplicate elements"

Code
Found in D:\strawberry\perl\lib\perlfaq4.pod 
How can I remove duplicate elements from a list or array?
(contributed by brian d foy)

Use a hash. When you think the words "unique" or "duplicated", think
"hash keys".

If you don't care about the order of the elements, you could just create
the hash then extract the keys. It's not important how you create that
hash: just that you use "keys" to get the unique elements.

my %hash = map { $_, 1 } @array;
# or a hash slice: @hash{ @array } = ();
# or a foreach: $hash{$_} = 1 foreach ( @array );

my @unique = keys %hash;

If you want to use a module, try the "uniq" function from
List::MoreUtils. In list context it returns the unique elements,
preserving their order in the list. In scalar context, it returns the
number of unique elements.

use List::MoreUtils qw(uniq);

my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7
my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7

You can also go through each element and skip the ones you've seen
before. Use a hash to keep track. The first time the loop sees an
element, that element has no key in %Seen. The "next" statement creates
the key and immediately uses its value, which is "undef", so the loop
continues to the "push" and increments the value for that key. The next
time the loop sees that same element, its key exists in the hash *and*
the value for that key is true (since it's not 0 or "undef"), so the
next skips that iteration and the loop goes to the next element.

my @unique = ();
my %seen = ();

foreach my $elem ( @array ) {
next if $seen{ $elem }++;
push @unique, $elem;
}

You can write this more briefly using a grep, which does the same thing.

my %seen = ();
my @unique = grep { ! $seen{ $_ }++ } @array;



lukdk
Novice

Sep 1, 2014, 8:25 AM

Post #3 of 4 (2163 views)
Re: [FishMonger] 2 questions about a while loop [In reply to] Can't Post

thank you for this usefull information.

this did the trick indeed. (and was also way faster to process my list)


Code
my @file=MOlib::read_file("input.txt"); 
my %hash = map {$_,1}@file;
my @result = keys %hash;



The list input.txt is just a plain text file:

hostname1
hostname1
hostname1
hostname1
hostname5
hostname7
hostname7
hostname18



The readfile code is:

package MOlib;


Code
sub read_file{ 
my $read_file=shift;
open (FILE, "<$read_file") or die "Can't open $read_file: $!\n";
my @file = <FILE>;
close FILE;
return @file;
}



When i just use this code:


Code
while (<@file>){ 
push (@result,$_)
}

My guess was that @file should be the same as @result. Why is that not the case?


Laurent_R
Veteran / Moderator

Sep 1, 2014, 9:50 AM

Post #4 of 4 (2156 views)
Re: [lukdk] 2 questions about a while loop [In reply to] Can't Post

This syntax:

Quote
while (<@file>){ # ...

is mixing up two different things. The <> operator for reading from a filehandle and some syntax to read items from an array.

Either your data elements are in an array named @file and then you can loop over the array with a while or better a for loop:

Code
push @result, $_ for @file;

or it is in a file and then you need tyo read from a filahandle:


Code
while (<$file_handle>) { 
# ...


Another point is that you should always:

Code
use strict; 
use warnings;

at the beginning of your programs. This will enable the compiler to help you detecting all kinds of errors.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives