in reply to reading file into an array

Just make that @lines and forget the split.

open (FILE, "$original") or die "Error: $!"; my @lines = <FILE>; close(FILE);
The diamond op does exactly what you wanted in array context.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: reading file into an array
by Anonymous Monk on May 31, 2004 at 23:52 UTC
    Thanks, I guess there's something else wrong. The array works fine but when I write it to an output file, it double spaces everything instead of prints an exact replicate. If I s/\n//, everything will be on the same line and that would be messed up too. Any suggestions?
    open (FILE, "> redo-output.txt") or die "Error: $!"; foreach (@lines) { print FILE "$_\n"; } close(FILE);
    Results:
    # Since the submit button was pushed, we have to check to see if t +he username # they typed exists. $passwords is actually the hash we made earl +ier, but since # we are using just ONE value we call our passwords hash as a scal +ar: $passwords. # To lookup a hash key to see if it exists, you use: if (exists $h +ash{"key"}) {}.
    Instead of:
    # Since the submit button was pushed, we have to check to see if the u +sername # they typed exists. $passwords is actually the hash we made earlier, + but since # we are using just ONE value we call our passwords hash as a scalar: +$passwords. # To lookup a hash key to see if it exists, you use: if (exists $hash{ +"key"}) {}.

      The lines in @lines still have their line endings attached, so when you print them with a newline you get doublespacing. Make that,

      for (@lines) { print FILE $_; }
      or just, print FILE @lines; You also could chomp @lines to remove the previous line ends - useful if you need to translate them.

      After Compline,
      Zaxo

      The elements of @lines has newlines. You either need to chomp them:

      chomp(my @lines = <FILE>)

      In which case you print them with:

      print FILE for @lines; # or, to be more verbose foreach my $line (@lines) { print FILE $line }

      Or, you can leave off the chomp, and use the loop:

      print FILE "$_\n" for @lines; # or, to be more verbose foreach my $line (@lines) { print FILE "$line\n"; }

      Either you've removed the newlines or you haven't, your foreach loop has to match.

      Of course, if this is all you're doing with @lines it'd be much simpler, and more kind to memory, to just read and write at the same time:

      print OUTPUT_FILE while <INPUT_FILE>; # or, to be more verbose while ($line = <INPUT_FILE>) { # manipulation of $line goes here. print OUTPUT_FILE $line; }

      perldoc -q 'entire file' covers this topic, 5.6.1's perldoc -q 'line in a file' helps to explain dealing with files, and 5.8.4's perldoc -q 'line in a file' tells you to use Tie::File.