Operating System - HP-UX
1751851 Members
5190 Online
108782 Solutions
New Discussion юеВ

Re: perl: delete element in an array?

 
SOLVED
Go to solution
Doug O'Leary
Honored Contributor

perl: delete element in an array?

Hey;

I find myself having to delete an arbitrary element in an array - not necessarily the first nor the last.

Is there some clever way of doing that short of

for (my $x=0; $x<$curr; $x++)
{ $new[$x] = $old[$x]; }
for (my $x=$curr+1; $x<$#old; $x++)
{ $new[$x-1] = $old[$x]; }
@old = @new;

And, no, I don't know if that works yet - that was just done off the fly. I'm curious if there's a different algorithm for doing this out there somewhere..

Thanks for any hints/tips/suggestions.

Doug

------
Senior UNIX Admin
O'Leary Computers Inc
linkedin: http://www.linkedin.com/dkoleary
Resume: http://www.olearycomputers.com/resume.html
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor
Solution

Re: perl: delete element in an array?

Hi Doug:

Have a look at 'splice':

# perl -le '@a=qw(a b c d e f);@a=splice(@a,3,2);print @a'
de

# perl -le '@a=qw(a b c d e f);@a=splice(@a,1,-1);print @a'
bcde

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: perl: delete element in an array?

Hi (again):

Sorry, I meant to add this too!

# perl -le '@a=qw(a b c d e f);splice(@a,3,2);print @a'
abcf

Regards!

...JRF...
Doug O'Leary
Honored Contributor

Re: perl: delete element in an array?

Hey;

That works pretty well; here's the playing around I did. This'll be exactly what I need. I appreciate it.

Doug

my @a = qw (one two three four five six seven eight nine ten );
my @b = @a;
my $cur = $ARGV[0];
print "$a[$cur]\n";
@a = splice(@b, 0, $cur);
print "A: @a" . "\n";
print "B: @b" . "\n";
push(@a, splice(@b,1));
print "A: @a" . "\n";
print "B: @b" . "\n";

./junk 3 # results in:
four
A: one two three
B: four five six seven eight nine ten

A: one two three five six seven eight nine ten
B: four

------
Senior UNIX Admin
O'Leary Computers Inc
linkedin: http://www.linkedin.com/dkoleary
Resume: http://www.olearycomputers.com/resume.html