On Tue, Apr 29, 2008 at 6:06 PM, melody <[EMAIL PROTECTED]> wrote:
snip
>  #!/usr/bin/perl
>  use warnings;
>  use strict;
snip

Good, keep this up

snip
>  my @array;
>  my @replacearray;
snip

Try to declare your variables where you initialize them.

snip
>  open FHR,'<',"repl.txt";
>  open OUT,'>>',"output.txt";
>  open IN,'<',"input.txt";
snip

Good use of the three argument version of open, but you should be
using lexical filehandles and checking for errors:

open my $fhr, "<", "repl.txt"
    or die "could not open repl.txt: $!";

Also, it is customary to write Perl programs as filters, that is they
work on data presented on STDIN or provided on the command line* and
print their results to STDOUT (with errors going to STDERR).  This
makes the program very flexible and cuts out a lot of file opening
code.

snip
>  @replacearray=<FHR>;
>  @array=<IN>;
>  for my $i(0..$#array)
snip

Unless you are certain that your files are small this is an incredibly
bad idea.  Use a while loop instead.  Also, don't use subscripts when
you can use the iterator version of for:

for my $value (@array) {
    #changes to $value also occur to $array[current position] through
the magic of aliasing
}

>  {
>   $array[$i]=~s/to be replaced/$replacearray[0]/gi;
>   push @replacearray, shift @replacearray;
>  }
>  my @result=grep(/[^\$]/,@array);
>  print OUT @result;
>
>
>  Can anyone point out to me what i am doing wrong??Thanks
snip

Off hand I would say that your problem is the newlines on both the
replace and the input lines.  You start with

"Text| to be replaced\n" and "replace1\n" and perform a substitution
that results in "Text| replace1\n\n".  The solution is to chomp the
replace lines as they are being read in:

my @replace = map { chomp; $_ } <$fhr>;

Here is my version of your code (note: <DATA> would be <> and you
wouldn't use the string/filehandle trick, they are there to make the
program self-contained for list purposes):

#!/usr/bin/perl

use strict;
use warnings;

my $replacefile = "replace1\nreplace2\nreplace3\n";

open my $fh, "<", \$replacefile
    or die "could not open the scalar \$replacefile as a file: $!";

my @replace = map { chomp; $_ } <$fh>;

while (<DATA>) {
        s/to be replaced/$replace[0]/gi;
        print;
        push @replace, shift @replace;
}

__DATA__
Text| to be replaced
Text| to be replaced
Text| to be replaced
Text| to be replaced
Text| to be replaced


* happily an empty <> exhibits this behavior (using STDIN if @ARGV is
empty or auto-opening the files in @ARGV if they are present)

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to