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: Intermediate:
creating arrays

 



jacksonpt
Deleted

Jul 25, 2000, 7:33 AM

Post #1 of 4 (497 views)
creating arrays Can't Post

I think that the only way I can ask this so that it makes any sense is to show an example of what I want to do.

Take a given input file:
This is line 1 of the input file
This is line 2 of the input file
...
...
...
This is line n-1
This is the last line of the file

and store it in arrays as such:
@array1 = (This, is, line, 1, of, the, input, file)
@array2 = (This, is, line, 2, of, the, input, file)
...
...
...
@arrayn-1 = (This, is, line, n-1)
@arrayn = (This, is, the, last, line, of, the, file)

which would result in the same number of arrays as the file has lines, with each array storing a single line of the input file. This would allow the file size to change, without requiring that the array creation process be changed.

Any help is appreciated.
Jackson


Cameron
Deleted

Jul 24, 2000, 10:40 PM

Post #2 of 4 (497 views)
Re: creating arrays [In reply to] Can't Post

@Array=map{[split]}<FILE>;

a little slower than the
while(<FH> ){chomp;push @data,[split]}
method.


mckhendry
Deleted

Jul 25, 2000, 8:08 AM

Post #3 of 4 (497 views)
Re: creating arrays [In reply to] Can't Post

I would suggest using a multidimensional array (an array of references to arrays).

You could do this as such:

#!/usr/bin/perl -w

use strict;

open (FILE, 'someFile.txt');

my @myData;

while (<FILE> )
{
chomp;
my @x = split (/ /, $_);
push (@myData, \@x); # pushes a reference to @x onto @myData
}

close FILE;

for my $line (@myData) # this looks at each line
{
for my $word (@{$line}) # this looks at each word
{
print "$word "; # prints each word and a space
}
print "\n"; # prints a newline characted at the end of each line
}


Each line is read in and the newline is chomped off. Then the line is split on spaces and the words are stored in @x. A reference to @x is pushed onto @myData. The I go into a for(each) loop to iterate through each reference. In the nested for(each) loop I cast the reference back to an array . . . and I think you can get the rest from there.
This is what I would suggest for what you are trying to do. I hope it helps, good luck

[This message has been edited by mckhendry (edited 07-25-2000).]


Kanji
User

Jul 25, 2000, 9:55 AM

Post #4 of 4 (497 views)
Re: creating arrays [In reply to] Can't Post

There's no need for @x.
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

while (<FILE> ) {
chomp;
push @MyData, [ split ];
}</pre><HR></BLOCKQUOTE>

 
 


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

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