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

Hello Monks, How can I do the following : I am reading somthing like this :
price product 200 shoe 20 shirt 10 shirt 5 hat
I want to store the products into an array without repeating the shirt twice , my array should look like this @products = ( shoe , shirt, hat ); Can someone give me a hint? thanks

Replies are listed 'Best First'.
Re: pushing to array
by Roger (Parson) on Mar 02, 2004 at 06:16 UTC
    Use a hash to eliminate duplicates. I have written a demo below to show how this can be done. There are other ways too of course.
    use strict; use warnings; use Data::Dumper; <DATA>; my @products = keys %{{ map { /^\d+\s+(\w+)$/ ? ($1,1) : () } <DATA> } +}; print Dumper(\@products); __DATA__ price product 200 shoe 20 shirt 10 shirt 5 hat

    And the output:
    $VAR1 = [ 'hat', 'shirt', 'shoe' ];

      ...in case you also get "belt buckle" as a product...then replace the above posted excellent code with "..*" where "\w+" is.
Re: pushing to array
by Tomte (Priest) on Mar 02, 2004 at 07:29 UTC

    Use ++Rogers advice, that is a hash to eliminate duplicates. If your data really looks like the given example, I found DBD::CSV to be very useful; this module basically allows you to access your csv-file data with DBD and SQL, making migration to a real database, if somewhere in time necessary, a very easy thing.

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

A reply falls below the community's threshold of quality. You may see it by logging in.