Perl Mail User wrote:
>
> Hello All,
Hello,
> I have a basic question, I am new to perl, and I would like to try
> and get a basic question answered, if possible. I have a file with
> about 63 lines in it, I am running it through a basic perl program
> that reads every line and prints it to the screen. I am trying to
> get the output of each line into an @array, but all I am getting is
> the last line in the file. Any help would be great.
>
> Script .... Like I said it is basic.
>
> __begin__
>
> #!/usr/bin/perl
>
> open(FILE, "file1.txt") || die "Can not open file. $! \n";
Very good.
> while ($line = <FILE>) {
> if ($line =~ /:58/) {
You imply above that you want every line from the file but this means
that you only want lines that have the string ':58' in them and if all
the lines have the string ':58' in them then what is the point in
testing for the string?
> #print $line; ## For Debugging Only
> foreach ($line) {
foreach (and for) are used to iterate through a list but since you only
have one item in the list and you are not using foreach to modify the
items in the list you don't really need a foreach loop here.
> @lines = $line;
This always assigns $line to $lines[0] so @lines will only have the last
value assigned to it. You probably want to use push() to assign $line
to the end of @lines without overwriting the previous elements of
@lines.
push @lines, $line;
> }
> }
> }
> print "@lines";
That is the same as:
print join( $", @lines );
And since $" normally has the value ' ' (a single space character) that
will add a space between all the lines from the file which you haven't
seen so far because you only had one line in @lines.
> __end__
This is probably what you want:
#!/usr/bin/perl
use warnings;
use strict;
open FILE, 'file1.txt' or die "Can not open file1.txt $! \n";
my @lines;
while ( my $line = <FILE> ) {
if ( $line =~ /:58/ ) {
#print $line; ## For Debugging Only
push @lines, $line;
}
}
print @lines;
Or you could simplify that a bit:
#!/usr/bin/perl
use warnings;
use strict;
open FILE, 'file1.txt' or die "Can not open file1.txt $! \n";
my @lines = grep /:58/, <FILE>;
print @lines;
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>