Hi Masato!

A few notes about your code.

On Wednesday 30 Dec 2009 09:40:56 Masato Sogame wrote:
> Hello,
> I want to replace text in file.
> So, I wrote subroutine like this:
> 
> sub replace_txt {
> my ($old,$new) = @_;

Your code needs indentation.

> open (FILE,"<$ARGV[0]");

See:

http://www.perlfoundation.org/perl5/index.cgi?two_argument_open

This should be replaced with:

<<<<<<
open my $file, "<", $ARGV[0]
        or die "Could not open '$file' - $!";
>>>>>>
I should note that it is bad form to access $ARGV[0] from the subroutine like 
that. I would do:

<<<<<
# in top-level
my ($filename) = @ARGV;

replace_text($filename, $old_text, $new_text);
>>>>>

> while(my $line = <FILE>) {
> $line =~ s/$old/$new/g;

Unless $old is a mini-regular-expression you should use \Q and \E here:

http://perldoc.perl.org/functions/quotemeta.html

> print $line;

Do you want to print it to STDOUT?

> }
> close(FILE);
> }
> 
> when I use this subroutine line this:
> &replace_txt('$a', '$b');

1. Don't use ampersand-subroutine calls:

http://www.perlfoundation.org/perl5/index.cgi?subroutines_called_with_the_ampersand

2. << '$a' >> is the literal string dollar-a. Maybe you want << "$a" >> or in 
this case simply << $a >> because you don't need to stringify a single string 
variable. Furthermore, you should not use $a and $b as lexical variables 
because they have special meaning in 
http://perldoc.perl.org/5.8.8/functions/sort.html and other functions. 

> but It doesn't work. $a in $ARGV[0] is still $a.
> 
> But, when I rewrite my subroutine like this:
> 
> sub replace_txt {
> open (FILE,"<$ARGV[0]");
> while(my $line = <FILE>) {
> $line =~ s/\$a/\$b/g;
> print $line;
> }
> close(FILE);
> }
> 
> It work fine. but I want to pass old and new text to subroutine as
>  argument. How to do this?
> I search about this but I can't find any help so please help me.
> 

I think the problem with your code is that you didn't use \Q and \E.

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Freecell Solver - http://fc-solve.berlios.de/

Bzr is slower than Subversion in combination with Sourceforge. 
( By: http://dazjorz.com/ )

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to