Dear all!
Please be patient with a beginner writing her first real Perl program.
I have a small problem where I can't find an answer in the books or
in the archives. I would appreciate a few hints.
I have a text file named "fruit", containing several lines, like this:
apples
oranges
peaches
apples
bananas
peaches
bananas
oranges
In my script I read the textfile into an array with the following code:
open(INPUT, "fruit") or die "Can't open file ($!)\n";
@fruit = <INPUT>;
close INPUT;
This code does what I want; it reads each line as an element of the
array @fruit, except for one thing: it puts a space in front of each
element from the second element onwards. If I print @fruit I get:
apples
oranges
peaches
apples
bananas
peaches
bananas
oranges
When I sort the array, it ignores the leading space. The result is:
apples
apples
bananas
bananas
oranges
oranges
peaches
peaches
When I compare the first and second line with each other, MacPerl
sees them as equal.
When I print the array back into a text file, the leading whitespace
is printed as well.
I don't want the space in front of the elements. How can I avoid this
from happening in the first place?
If I can't avoid this, I want to get rid of it using a regular
expression. Again I am stumped. My try was:
foreach $line (@fruit) {
if ($line =~ /^ /) {
$line =~ s/^ //g ;
}
}
But it changes nothing.
Please help me writing a regular expression for searching and
replacing in each element of an array.
I use BBedit 6 as text editor and MacPerl 5.2.0r4.
Kind regards
Anette