Ling F. Zhang wrote:
> I have the following problem:
>
> I just read in a file <FILE>...
> in ONE of line of the file, there is a word I need to
> substitute...
> but I realize that:
> $a = <FILE> would assign $a the first line of the file
> @a = <FILE> world assign each line of the file as an
> element of @a...
> now...s/search/replace/ only works for string...
> is there a way to avoid looping through the file (or
> elements of @a to do this search/replace?)
> now the way I am doing is:
>
> foreach $m (@a){
>  $m =~ s/search/replace/;
> }
>
> is there way to avoid this loop? (such as reading the
> whole file into a single scalar?)

Hi Ling.

Yes, there is, but I don't understand why you want to avoid the
loop. The processing will be the same whether you expand it
in-line (by processing one Very Big Record instead of many
bite-size ones) or hide it syntactically (behind something like
'map'). It also depends on what you want to do with the data
once you've modified it. As you say,

  my @a = <FILE>

reads the entire file as records into an array, but this is
more than likely unnecessary and should be attempted only if
you can guarantee that your file is a reasonable size compared
with your available memory. (For production code you should
check the file's size before you read it.) There is a simple
way to read the file into a single scalar, but you probably
don't need it.

It looks like you probably want to edit an existing file and
write a modified version, in which case you need something like

  open OUT, "> newfile" or die $!;

  while (defined (my $m = <FILE>)) {
    $m =~ s/search/replace/;
    print OUT $m;
  }

  close OUT;

which processes the file one record at a time with negliglible
speed penalty. It can be written more idiomatically and succinctly
using the $_ variable instead of your own $m

  open OUT, "> newfile" or die $!;

  while (<FILE>) {
    s/search/replace/;
    print OUT;
  }

  close OUT;

I hope this helps. if this isn't what you want, come back and we'll
try again.

Oh, and

  use strict;   # always
  use warnings; # usually

:)

Rob




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to