Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Perl (http://www.programmingforums.org/forum21.html)
-   -   How To Split Array Into Two Seperate Arrays? (http://www.programmingforums.org/showthread.php?t=3644)

blackmagic Apr 29th, 2005 9:50 AM

How To Split Array Into Two Seperate Arrays?
 
I was wondering how, if i had an array of a fair few values (say about 20 for arguments sake), called @example

How would i divide this array into two seperate arrays, as in, the first 5 values of the array were in @part1 and the second 15 in @part2. Is there a function, or failing that a good method to do this.

The context in which i am asking, is i wish to read the contents of a text file, and edit 5 or so lines in the middle, but leave the rest the same. I plan to do this by reading the whole text file into an array:

:

open(INFILE,">empayslips.txt");
my @wholefile = <INFILE>;
...


I then plan to split the array into all the values before the data i want to edit and all the data i don't want to edit (this will likely need to be done with two 'splits').

Anyhow, if you know how to divide arrays like afforementioned, any assistance would be greatly appreciated.

mackenga Apr 30th, 2005 2:16 PM

You could use array slices. With your 20-element @example array example, to get the first five items into @first and the rest into @second, I believe you could do:

:

@first = @example[0..4];
@second = @example[5..];


I'm not 100% sure of the syntax off the top of my head (not sure if just leaving off the upper bound is the right thing to do in the second line there). But I definitely think array slices are your answer.

Hope this helps.

P.S.: I noticed a bug in your code there; if ">" is the first character of the 'filename' argument to open(), it opens for writing, creating the file or truncating it to zero length. What you want is "<".


All times are GMT -5. The time now is 4:12 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC