SPUG: Re: re-size array

michaelrwolf at att.net michaelrwolf at att.net
Mon Oct 11 16:58:51 CDT 2004

Pedant alert -- I'm an isstructor, too.

Don't get the words confused: splice and slice.

splice -- a built-in function

slice -- a concept.  An indexing (or lookup) operation on an array (or hash) that returns a list.

    @array_slice = @array[index list goes here];
    @hash_slice = @hash{key list goes here};

Brian's grep solution:

    For example this would work if you just want to remove every other

	@array = grep { %i++ % 2 }  @array;

Brian's solution used grep to pass every other array element.  (Code review note:  I'd add a "my $i=0" line before the grep line to be explicit about where $i starts.)

The following alternative uses grep to generate the indices for an array slice.

# As a one-liner.
@new_array = @old_array[ grep { $_ % 2 } 0 .. @old_array - 1 ];

# As a two-liner.
@indices = grep { $_ % 2 } 0 .. @old_array - 1;
@new_array = @old_array[@indices]; 


There's probably a bit more of a memory issue for my solution.  It has to hold the @indices array in memory, then the slice'd list in memory before it gets assigned.  For big arrays, this may be an issue.  You're probably on the cusp of where I'd benchmark it to see how it worked.  Otherwise, I'd be tempted to write the one that's more likely to make sense to me in 2 weeks or  6 months when I come back to maintain the code.

> _____________________________________________________________
> 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

-------------- next part --------------
An embedded message was scrubbed...
From: Brian Hatch <bri at ifokr.org>
Subject: Re: SPUG: re-size array
Date: Mon, 11 Oct 2004 17:34:56 +0000
Size: 1942
Url: http://mail.pm.org/archives/spug-list/attachments/20041011/6f3f809e/attachment.eml

More information about the spug-list mailing list