in reply to Problem with reading the total file into variable
Hello ravi45722,
I see two problems. First, print takes a list as its argument; or, putting that round the other way, print imposes list context on its argument(s). So
print <MYFILE>;
reads in the whole of the rest of the file (after the first line, which was already read in via the <MYFILE> in the while condition) and prints that on the first iteration of the loop.
Second, the line:
$data = join "", <MYFILE>;
does nothing, because the MYFILE filehandle is already pointing to the end of the file by the time it reaches this line. But if you were actually printing just the line already read in the while condition, the join would itself eat up the rest of the file, because it too imposes list context on its argument(s).
I think you’re looking for something like this, which uses concatenation in place of join:
use strict; use warnings; my $data; while (<DATA>) { print; $data .= $_; } print $data, "\n"; __DATA__ 1st line 2nd line 3rd line 4th line End of file
Output:
17:08 >perl 1355_SoPW.pl 1st line 2nd line 3rd line 4th line End of file 1st line 2nd line 3rd line 4th line End of file 17:08 >
Note: I’ve taken out the call to chomp; why remove the newline if you want to put it back again when printing and concatenating?
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|