CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
List to array

 



David4
Deleted

Mar 13, 2000, 9:27 PM

Post #1 of 4 (667 views)
List to array Can't Post

I'm trying to convert a list to an array:

fruitfile2.txt:

big red apples
large juicy oranges
small firm peaches

to:

@fruits = ('big red apples', 'large juicy oranges', 'small firm peaches')


Here's the program I used:

$tall = "fruitfile2.txt";

open(INFILE, $tall) or die "Couldn't open the ". "fruitfile2.txt file for writing.\n";

while(<INFILE> ){
$Theline = $_;

@fruits = split(/^/m, $Theline);

print @fruits[0];

}

close(INFILE);

Can you tell me where's the problem? The books I have are not doing much good. Thank you!


Cure
User

Mar 13, 2000, 9:52 PM

Post #2 of 4 (667 views)
Re: List to array [In reply to] Can't Post

Hi

$tall = 'fruitfile2.txt';

open(CURE, "<$tall") or die "Couldn't open the fruitfile2.txt file for writing.$!\n";

while (<CURE> )
{
push @fruits,$_;
}
close(INFILE);

print @fruits;


Cure


darian
Deleted

Mar 14, 2000, 2:04 AM

Post #3 of 4 (667 views)
Re: List to array [In reply to] Can't Post

David4,
Actualy Cure's solution is sort of entering them manually. When using the while statement you are taking the file in line by line and storeing the first line in $_ then using the push statement to add the first line (now stored in $_) to @fruits. Then the while statement takes in the second line and does the same. And so on through the whole file.

You can also do it this way:

$tall = "fruitfile2.txt";

open(INFILE, $tall) or die "Couldn't open the ". "fruitfile2.txt file for writing.\n";
@fruits = <INFILE>;
close(INFILE);

However this slurps in the file as one and is not very wise. You will see lots of other scripts out there however that use this method. It is easier to write but takes more system resources to read in an entire file instead of one line at a time. And when you get to very large files, say 3megs you can cause a bit of havoc on your sever.



David4
Deleted

Mar 14, 2000, 10:54 AM

Post #4 of 4 (667 views)
Re: List to array [In reply to] Can't Post

Hi Cure,

Thank you for the fast response.

I thought (push ARRAY, LIST) the LIST had to be entered manually like the examples in my book. Your solution has made a good impression on me. I think it's going to help me in understanding other Perl functions a little better. Thank you for helping me in learning Perl.

David4

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives