| |||||||||||
| |||||||||||
script Posted by Tim (Tim), 16 October 2007 i'm working in perl.i want to compare the values of an array. The input file may contain datas like this: test test help text now i want to compare the values of 1 and 2 then 2 and so on. can anyone help me? Posted by KevinAD (KevinAD), 16 October 2007 Your question is confusing. You say you want to compare the values of an array, but then say the input file may contain....Are you comparing the lines of a file or the elements of an array? Or have you read the lines of a file into an array? If so: Code:
Keep in mind, arrays start at 0 (zero) so when the output says 0 it corresponds to line number one of a file read into an array. Posted by Tim (Tim), 16 October 2007 hi,As u have mentioned i'm reading the whole file into an array. i have pasted the code what i have tried. $file = 'c:/test8.txt'; open(INFILE, $file); foreach (<INFILE>) { @dnames=<INFILE>; for($j=1;$j<$dnames;$j++) { for($k=j+1;$k<@dnames;$k++) { if($dnames[j] eq $dnames[k]) { print "compared"; } } } } Posted by admin (Graham Ellis), 16 October 2007 if($dnames[j] eq $dnames[k]) should be if($dnames[$j] eq $dnames[$k]) for starters. You then want to eliminate checking each item against itself, and also put a not of just WHICH ones are the same if you find an identical pair. Posted by KevinAD (KevinAD), 16 October 2007 on 10/16/07 at 07:04:21, Tim wrote:
I think my code showed you how to do exactly what you want. Your code is wrong in several ways. Posted by george_Ball (george), 17 October 2007 I'm led to wonder what the overall aim of the code is? Is it to detect duplicates in input? If so then this algorithm is not the best choice as it certainly won't scale...If it's duplicates you are after, why not use a hash? my %lines = (); # keeps use strict happy ![]() my $line; # ditto... while ( defined( $line = <INPUT> ) ) { if ( exists( $lines{$line} ) { print "$line exists already\n"; } else { $lines{$line}++; } } Now keys %lines has a list of all the unique lines in your input, and the value of each element in the hash will be the number of times the line was seen... Of course that may not be what you want, in which case ignore This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |