Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

split an array

Status
Not open for further replies.

dkin

Programmer
Dec 11, 2002
39
0
0
ES
How can I split an array so I will get two new arrays. One will be based on the odd line numbers content and the other one for even line numbers

main array
1
2
3
4
5
6

new odd array
1
3
5

new even array
2
4
6

Thanks
 
$j=0
$k=0
for ($i=0;$i<=@nums;$i++)
{
if (($i%2)!=0) #odd numbers
{
$odds[$j]=($nums[$i]); #array with odds
$j++
}
else #even nums
{
$evens[$k]=($nums[$i]);
$k++;
}
}
Might be buggy, I'm a beginner myself. ;-)
But should do it.

Andreas Galambos
EDP / Technical Support Specialist
(andreas.galambos@bowneglobal.de)
HP:
 
I think dkin wants the values of the odd indexes in 1 and the even indexes in the other...not the odd values in one and even values in another...

If you want odd/even indexes, do this:

Code:
@list=qw(a b c d e f);
for($i=0;$i<=$#list;$i++) {
    if ($i/2==int($i/2)) {push(@evens,$list[$i])}
    else                 {push(@odds ,$list[$i])}
}

print &quot;odds  are : &quot; . (join &quot; &quot;,@odds)  . &quot;\n&quot;;
print &quot;evens are : &quot; . (join &quot; &quot;,@evens) . &quot;\n&quot;;

which would produce:

odds are : b d f
evens are : a c e
 
You could use grep.
Code:
#!perl
use strict;

my @a=(1..6);
my @odds=grep {$_ % 2} @a;
my @evens=grep {!($_ % 2)} @a;

print @odds, &quot;\n&quot;, @evens;
Prints
135
246
 
Well, that would put the odd *values* into one array and the even *values* into the other...not the indicies...

actually, looking closer at MakeItSo's code I see it's actually right..sorry about that!
 
According to the example in the original post, it is the odd *values* that are wanted in the &quot;odds&quot; array and the even *values* that are wanted in the &quot;evens&quot; array. That's what my example does.
 
Instead of arguing, why don't we let dkin tell us, as the original poster? What do you say, dkin?
Do you want the odd *values* in one array and the even *values* in another array, or the elements with odd *indices* in one array and the elements with even *indices* in the other array? It's your question, so please tell us.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top