in reply to Print hash except first value

Some alternatives:

my $first = 1; for my $n (sort { $hash{$a} <=> $hash{$b} } keys %hash){ if ($first) { $first = 0; next; } ... }
my @names_by_val = sort { $hash{$a} <=> $hash{$b} } keys %hash; shift(@names_by_val); for my $n (@names_by_val) { ... }
my @names_by_val = sort { $hash{$a} <=> $hash{$b} } keys %hash; for my $n (@names_by_val[1..$#names]) { ... }

A hash isn't needed at all.

my %hash; foreach my $n (@names){ my $r = int(rand($range))+$min; $hash{$n}=$r; } my @names_by_val = sort { $hash{$a} <=> $hash{$b} } keys %hash;

can be replaced with

use List::Util qw( shuffle ); my @shuffled_names = shuffle @names;

Update: Doesn't answer the question.

Replies are listed 'Best First'.
Re^2: Print hash except first value
by xhunter (Sexton) on Dec 21, 2008 at 17:37 UTC

    Here's a way using two arrays. You can iterate over the index of the elements in each array while preserving the order of the @names.

    my @names = qw(Greg Caroline Joe Dom Mary Gerard Mark Clare Adam Damia +n Conor Cassie John Jane Mike); my $max_rand = 8999; my $min_rand = 0; my @random_array = map{ int(rand($max_rand + 1)) + $min_rand } @names; foreach my $index (0..$#names) { print "$names[$index], $random_array[$index]\n"; }

    In addition, you could easily not print a line based on its index number. For example inside the print loop add:

    my $skip_index = 0; next if $index == $skip_index;
Re^2: Print hash except first value
by joec_ (Scribe) on Dec 20, 2008 at 22:23 UTC
    thanks for the quick reply, what does each section of your code do?
      They iterate over the (keys of the) hash, skipping the first one

      Update: ...which I now see isn't what you asked. In fact, I don't know what you are trying to do. I don't see what the hash has to do with anything. As best as I can tell, you want a variation of

      for my $skip (0..$#names) { print("-------\n"); for my $i (0..$#names) { next if $i == $skip; my $n = $names[$i]; print("$n, $hash{$n}\n"); } print("* Note removal of element $skip\n"); print("\n"); }
        What i want to do is:
        1. Given the names in the array, assign a random 4 digit number to each one (which i could do with a hash).
        2. Print out that full list of names and numbers
        3. Print out that list of names and numbers but without the first element Greg
        4. Print out that list of names and numbers but without the second element Caroline
        5. Do that for the whole array.

        Eventually, i will get round to emailing each person in the array, a list without the their name and number in, so as they dont know what it is.

        Hope that is clearer