biohisham has asked for the wisdom of the Perl Monks concerning the following question:

Part of the problem I am stuck in is to use an array element as a hashkey, I managed to create this array, however, the elements in the array are repeating, I want to modify the code such that for every element in @continents there is only one single occurrence within the array itself (purging out repeating elements).

My plan is to use an array element as a key in a hash and this hash would hold an anonymous array member corresponding to a country (Would work on that afterwards).

#!/usr/local/bin/perl use strict; my @continents; my($key, $value); while(<DATA>){ chomp; my($key, $val)=split /:/; push @continents,$key; } print "@continents\n"; __DATA__ Europe:Germany Europe:France Asia:India Europe:Italy Asia:Japan Asia:Indonesia

Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.

Replies are listed 'Best First'.
Re: Deleting repeating array elements
by johngg (Canon) on Aug 17, 2009 at 22:46 UTC

    I wonder if this is what you are aiming to do.

    use strict; use warnings; use Data::Dumper; my %continents; while ( <DATA> ) { chomp; my( $continent, $country ) = split m{:}; push @{ $continents{ $continent } }, $country; } print Data::Dumper->Dumpxs( [ \ %continents ], [ qw{ *continents } ] ); __DATA__ Europe:Germany Europe:France Asia:India Europe:Italy Asia:Japan Asia:Indonesia

    The output.

    %continents = ( 'Europe' => [ 'Germany', 'France', 'Italy' ], 'Asia' => [ 'India', 'Japan', 'Indonesia' ] );

    I hope I have guessed correctly and this is of some help.

    Cheers,

    JohnGG

      This is exactly the sort of code steps that I got in my mind, I remember having read a similar solution at some tutorials but I could not retrieve it today that I needed it, what a shame. Thanks a lot, I appreciate this :)


      Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.
Re: Deleting repeating array elements
by toolic (Bishop) on Aug 17, 2009 at 21:27 UTC
Re: Deleting repeating array elements
by JavaFan (Canon) on Aug 17, 2009 at 21:17 UTC
    perldoc -q duplicate contains the answer of your question. But your code suggest you should use a hash instead of an array.
Re: Deleting repeating array elements
by bichonfrise74 (Vicar) on Aug 17, 2009 at 21:56 UTC
    Consider something like this.
    #!/usr/bin/perl use strict; my %continent_of; while( <DATA>) { my ($key) = (split /:/)[0]; $continent_of{$key}++; } print join "\n", sort keys %continent_of; __DATA__ Europe:Germany Europe:France Asia:India Europe:Italy Asia:Japan Asia:Indonesia