SPUG: re-size array

DeRykus, Charles E charles.e.derykus at boeing.com
Mon Oct 11 18:35:34 CDT 2004



You can juke the "odd no. of elements in hash assigment" warning
and maintain hash insert ordering too:

tie my %hash, 'Tie::IxHash' or die;
%hash = @array % 2 ? (@array,undef) : @array;
my @odd = keys %hash; my @even= values %hash;
$#even-- unless defined $even[-1];

(Assuming @array won't produce key duplicates
that'd vanish when hashified)


-----Original Message-----
From: Colin Meyer [mailto:cmeyer at helvella.org] 
Sent: Monday, October 11, 2004 3:45 PM
To: michaelrwolf at att.net
Cc: SPUG; Luis Medrano
Subject: Re: SPUG: re-size array


On Mon, Oct 11, 2004 at 10:03:10PM +0000, Michael R. Wolf wrote:
> 
> 
> 
> > %hash = @array;
> > 
> > @even = keys %hash;
> > @odd  = values %hash;
> 
> Tricky!  I like it.
> 
> But beware. It only works if you don't care about the ordering of the 
> @even or @odd arrays. If you merely need to consider them as sets 
> (collections), this will work. Otherwise, the ordering has been lost 
> by creating a hash out of it.

Also worth noting is that you will get a bogus undef in the @odd array, if there were an odd number of elements in @array.

> 
> It'll probably take a not-so-insignificant amount of time/CPU to build 
> that hash.

I wouldn't think so. Perl hashes are pretty speedy to use. But just to be sure, here's a test of hashes vs iterating through the list:

        Rate iter hash
iter 11962/s   -- -14%
hash 13831/s  16%   --

Hashes 14% faster than iterating (at least by my cheap test).

-Colin.

#!/usr/bin/perl
                                                                                
use Benchmark ':all';
                                                                                
my @a = 1..100;
                                                                                
cmpthese( 100_000, { iter => \&oddeven_iterate, hash => \&oddeven_hash } );
                                                                                
sub oddeven_hash {
  my ( $o, $e, %h );
  %h = @a;
  $o = [ keys %h ];
  $e = [ values %h ];
  return $e, $o;
}
                                                                                
sub oddeven_iterate {
  my ( $o, $e );
  push @{ $_ % 2 ? $o : $e }, $a[$_] for 0..$#a;
  return $e, $o;
}
_____________________________________________________________
Seattle Perl Users Group Mailing List  
POST TO: spug-list at mail.pm.org  http://spugwiki.perlocity.org ACCOUNT CONFIG: http://mail.pm.org/mailman/listinfo/spug-list
MEETINGS: 3rd Tuesdays, Location Unknown
WEB PAGE: http://www.seattleperl.org



More information about the spug-list mailing list