in reply to from array to hash

%b = map { $_ => 1 } grep defined, @a;

or

%b = map { defined ? ($_ => 1) : () } @a;

or you could avoid getting undef in the first place by using splice instead of delete or undef to delete the element from the array:

@a = qw( a b c d ); # Delete 1 starting at index 2. # What used to be at index 3 is now at index 2. splice(@a, 2, 1); print("\@a has ", scalar(@a), "elements.\n");

Replies are listed 'Best First'.
Re^2: from array to hash
by jeanluca (Deacon) on Mar 09, 2006 at 15:44 UTC
    Thanks, but what if the hash already has some values, like:
    #! /usr/bin/perl @a = qw(a b c d ); $b{x} = 10 ; %b = map { $_, 1} splice(@a, 0, scalar(@a) ); print "$_ --> $b{$_}\n" foreach (keys %b) ;
    all values of %b are erased using map.....
    Furthermore, is scalar(@a) really necessary, or can you as well do @a ?

    Luca
      In that case, you can use a loop instead:

      $b{$_} = 1 for grep defined, @a;

      You've severly misunderstood the use of splice. Did you read the docs?

      @a = qw(a b c d ); undef $a[2]; $b{x} = 10 ; $b{$_} = 1 foreach grep defined, @a;

      or

      @a = qw(a b c d ); splice(@a, 2, 1); $b{x} = 10 ; $b{$_} = 1 foreach @a;