|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stay one step ahead of the competition. Evaluate and give feedback
on some of the hottest web development tools on the market today.
Make your opinion heard! Click
Here
|
|
#1
|
|||
|
|||
|
I know this is an easy question but i am having a mind block right now on how to do this...
If i open a file and store the contents into an array how can i get only the first 50 items in the array out and into another array ? Thanks in advance, Drew |
|
#2
|
||||
|
||||
|
Here's one approach:
Code:
$i = 0;
@newdata = ();
open(FILE,"$some_file") || die $!;
@data = <FILE>;
close (FILE);
LOOP: foreach (@data) {
if ($i > 50) { last LOOP; }
if ($i < 50) {
push(@newdata,$_);
}
$i++;
}
Now the @newdata array contains the first 50 lines from the @data arry. Mickalo [Edited by mickalo on 02-09-2001 at 02:28 PM]
__________________
Thunder Rain Internet Publishing Custom Programming & Database development Providing Personal/Business Internet Solutions that work! |
|
#3
|
|||
|
|||
|
As with all common tasks, there's a simple way to do it in Perl.
Code:
@a = qw{0 1 2 3 4 5 6 7 8 9 10};
@b = @a[0..4];
foreach (@b) {
print;
}
@a has 11 elements, the numbers 0 to 10. We then assign a slice of elements 0 to 4 to @b. In your example, you'd want to slice from [0..49] to get the first 50 elements. You can also select individual elements of an array like this. eg. @b = @a[1,5,21]; # just elements 1, 5 and 21. The .. operator isn't specifically associated with array slices, it just creates a list of values between the first and last, inclusive. In the code example above I could have loaded the @a array like this: @a = (0..10); but I wrote out all the values for clarity. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Perl Programming > An Easy one..(array) |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|