On Tue, Apr 29, 2008 at 6:06 PM, melody <sreevidhyas@[EMAIL PROTECTED]
> wrote:
snip
> #!/usr/bin/perl
> use warnings;
> use strict;
snip
Good, keep this up
snip
> my @[EMAIL PROTECTED]
> my @[EMAIL PROTECTED]
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
> @[EMAIL PROTECTED]
>;
> @[EMAIL PROTECTED]
>;
> 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 (@[EMAIL PROTECTED]
) {
#changes to $value also occur to $array[current position] through
the magic of aliasing
}
> {
> $array[$i]=~s/to be replaced/$replacearray[0]/gi;
> push @[EMAIL PROTECTED]
****ft @[EMAIL PROTECTED]
> }
> my @[EMAIL PROTECTED]
(/[^\$]/,@[EMAIL PROTECTED]
);
> print OUT @[EMAIL PROTECTED]
>
>
> 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 @[EMAIL PROTECTED]
= 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 @[EMAIL PROTECTED]
= map { chomp; $_ } <$fh>;
while (<DATA>) {
s/to be replaced/$replace[0]/gi;
print;
push @[EMAIL PROTECTED]
****ft @[EMAIL PROTECTED]
| 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 @[EMAIL PROTECTED]
is
empty or auto-opening the files in @[EMAIL PROTECTED]
if they are present)
--
Chas. Owens
wonkden.net
The most im****tant skill a programmer can have is the ability to read.


|