Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

jimberger 2

Status
Not open for further replies.

jimberger

Programmer
Joined
Jul 5, 2001
Messages
222
Location
GB
hi ,

is they anyway in perl to remove repeating groups in an array, like a function call called unique or by placing the data into a set like in c++,

thanks
 
No way to do that in Perl that I know of - but a hash would do that for you. Using a hash, any key will only exist once - so if you make 3 value assignments using the same key, only the last one will be saved for that key.
Hardy Merrill
Mission Critical Linux, Inc.
 
cheers hardy - i understand what you mean but how do i then access the key and print the key out. for example i have the hash:

hash = ($reportNo => {
'Type' => $Type,
'Year' => $Year,
'Link' => $Link,
'Authors' => $Authors,
'Desc' => $Description
}
);


if i want to access an element i do:

$Link = $hash{$reportNo}{'Link'};

but how do i print the unquie key ($reportNo) out to screen?

thanks
 
Given this hash:

%hash = ($reportNo => {
'Type' => $Type,
'Year' => $Year,
'Link' => $Link,
'Authors' => $Authors,
'Desc' => $Description
}
);


Here's how you can iterate through it:

foreach $key (keys %hash) {
print &quot;Key=<$key>\n&quot;;
foreach $key2 (keys %{$hash{$key}}) {
print &quot; Key2=<$key2>, Value=<$hash{$key}{$key2}>\n&quot;;
}
}

The first foreach uses the &quot;keys&quot; command - the result will be that each iteration of the outer foreach will get the value of one of the keys of the %hash, which really is $reportNo. The inner foreach iterates through each of the fields (Type, Year, etc.) in the anonymous hash.

Read up on hashes - not sure what platform you're on, but on Linux I can access the Perl documentation by doing &quot;perldoc perl&quot; - that will give you an index of other perldoc books to look at. For example, from the &quot;perldoc perl&quot; I found that data structures are in the &quot;perldata&quot; perldoc, so to see those(which includes hashes), I did &quot;perldoc perldata&quot;. You get the idea.

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
Here's a function that will remove all duplicates in an array. It uses a temporary hash, but returns an array.
Code:
sub unique {
my(@list) = @_;
my %list = map { $_ => 1 } @list;
return sort keys %list;
} # unique
You use it like this:
Code:
@array = unique(@arrary);

Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top