Perl: varible-sized arrays?

How do you store strings in a variable-sized array?

Background:
I wrote a program earlier today to work with a very large text file. I chose Perl because it lets me do some nice formatting on the text I grab, instead of just using a shell script to con'cat'enate egrep results.

The program worked pretty nicely, outputting html that is displayed in the browser. (This is useful, not just pretty: the generated web page has many links, and it's much more convenient to click than copy/paste/modify.) But I wanted to modify the results based on whether there is a match or not for each section. If there are 1 or more matches, write the header, the formatted matches, and the footer; otherwise write nothing.

I have a large @all array which will contain a few (maybe 0-100) matches for a particular regular expression. I'd like to store the matches -- actually, formatted text based on those matches -- in an array so I can work with them later. What's the best way to do this? I'd like to get better with perl rather than just emulate C in perl, so I thought it might be a good idea to post here rather than just butt my head against the language a bit longer.

Your question is a bit vague, but to add new data to the end of an array you can the push() function:

@array = ('foo');
push @array,'bar';

now the array has ('foo', 'bar')

You can just keep adding to an array like this until you have used all the available memory, although in practice you don't want to do that. Its just that perl puts no limitations on the size of an array.

Here's a short script that should give you a few ideas:

$ 
$ perl -e '$_="ant bat cat dog eel";
>          while (/(\w+)/g) {  # match a word repeatedly in $_
>            push @x, $1;      # push the matched word into the array @x
>          }                   # array @x now has 5 elements - ant, bat, cat, dog, eel
>          foreach $i (@x) {   # loop through the elements of array @x
>            print $i, "\n";   # print the array element
>          }'
ant
bat
cat
dog
eel
$ 

tyler_durden