kadau wrote:
> I hope this is an appropriate group to post in, my apologies if it is
> not. I would to to be able to read from a file and be able to locate all
> the instances of a substring within it, save it in an array, then print
> it out.
Are you sure that's _what_ you want to do and not _how_ you think you
can do something? Anyhow I think you are expressing what you want
carefully. In programming, precisely understanding what it is you want
to do is often 90% of doing it.
> I am fine with this except finding all the matches. Could anyone
> explain how to do this with index?
To do that you'd need to slurp the whole file into a string (see FAQ)
but this is far form a natural approach.
my $pos=0;
while ( ( $pos = index( $file_content, $target, $pos )) > -1 ) {
# Do stuff with $file_content and $pos
}
> Or is there some other way (please
> try to keep it simple if you can
Yes there are much simpler ways. But first you need to step back and
consider what you really want to do.
> I want to locate & save to an array all lines begging with "*".
Hmmm... ok now we are perhaps getting closer.
my @lines_starting_with_asterisk;
local *_;
while(<FILE>) {
push @lines_starting_with_asterisk => $_ if /^\*/;
}
> I
> presume I will then be able to use split to get the raw prices out of
> the array (in between the "<").
But why do you think you need an array? Can you not simply process the
stuff as you read it from the file?
The split() function is good if you have a delimited list of arbitrary
length but the usual way to structured text in Perl is just the simple
pattern match. Simply write a pattern that matches the lines you are
interested in and captures the interesting parts of the line.
local *_;
while(<FILE>) {
next unless my ($item, $price)=/^\*(.*?)<(.*?)</;
# Do stuff with $item and $price.
}