in reply to slurping into a substring'ed' array

Here's a rather IMHO long winded way to do it:

#!/usr/bin/perl -w my @foo=('A1','A2','A3','B5','B6','B7','C789','C790'); my %letters=(); my @muut = map { $letters{substr($_,0,1)}++ } @foo; my @final = sort keys %letters; printf "%s\n",join(",",@final);
Hope this helps.

Replies are listed 'Best First'.
Re: Re: slurping into a substring'ed' array
by dragonchild (Archbishop) on Apr 26, 2004 at 15:20 UTC
    Technically, you don't need the ++. Just by accessing the hash value creates the key. So, you could do something like:
    $letters{substr($_,0,1)} for @foo;

    Though, it is polite to explicitly set it to undef, unless you need the count. :-)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      Just by accessing the hash value creates the key.
      $letters{substr($_,0,1)} for @foo;
      that gives:
      Useless use of hash element in void context
      besides that, just accessing the hash value does not create it. autovivification only happens if you're accessing an element one level deeper (e.g. in a HoH)
      dear all respondees,

      thanks for your fast responses, i was in the proces of testing it myself, and had got as far as:

      my %seen; my @sorted = sort($a <=> $b) grep{ $seen{$_}++ } map {substr($_,0,1)} +@original_array;

      when i realised y'all were on the board already!!

      I just wanted to point out that my code above printed out this list:

      A,A,B,B,C

      So why did it only print out the extra As and Bs? Out of curiosity.

      Thanks again for your help.

      Sam

        grep checks against %seen and, the first time, sees that it's zero (false), so doesn't pass it through. The second time, it's non-zero (true), so it passes that value through. The third and subsequent times, it's still true. Your grep would have dropped all unique values. (If you had a D123, for instance, it would have been missed.)

        If you absolutely have to have it in one line, provide a function called unique() and do something like:

        sub unique { my %x; @x{@_} = @_; values %x } my @sorted = sort { $a cmp $b } unique map { substr($_, 0, 1 ) } @original;

        ------
        We are the carpenters and bricklayers of the Information Age.

        Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose