manish.rathi has asked for the wisdom of the Perl Monks concerning the following question:

I want to enter file names to be worked with dynamically i.e I dont want to provide file names at the begnning of the program. I have written following code, but its not working properly.

print "file1 ="; $file1=<stdin>; print "file2 =" ; $file2=<stdin>; @ARGV = {"$file1", "$file2"} ; chomp($remove = <stdin>); chomp($replace = <stdin>); while(defined($line=<>)){ $line =~ s/$remove/$replace/g; print "$line"; }

Pls let me know whats wrong.

Replies are listed 'Best First'.
Re: providing filenames dynamically
by ysth (Canon) on Feb 24, 2009 at 05:33 UTC
Re: providing filenames dynamically
by balakrishnan (Monk) on Feb 24, 2009 at 06:01 UTC
    You have to change your code like,
    print "file1 ="; $file1=<stdin>; print "file2 =" ; $file2=<stdin>; @ARGV = ("$file1", "$file2") ; chomp($remove = <stdin>); chomp($replace = <stdin>); while(defined($line=<>)){ $line =~ s/$remove/$replace/g; print "$line"; }
    When your code seems not giving the expected result, you can use the perl debugger to find out issue.
    I debugged the code, after made the change from {} to ()
    main::(./dynamic_file.pl:22): print "file1 ="; DB<1> n main::(./dynamic_file.pl:23): $file1=<stdin>; DB<1> n file1 =file1 main::(./dynamic_file.pl:24): print "file2 =" ; DB<1> n main::(./dynamic_file.pl:25): $file2=<stdin>; DB<1> n file2 =file2 main::(./dynamic_file.pl:26): @ARGV = ("$file1", "$file2") ; DB<1> n main::(./dynamic_file.pl:27): chomp($remove = <stdin>); DB<1> p @ARGV file1 file2
Re: providing filenames dynamically
by PoorLuzer (Beadle) on Feb 24, 2009 at 05:30 UTC
    chomp on filename input from stdin!
Re: providing filenames dynamically
by Anonymous Monk on Feb 24, 2009 at 08:49 UTC
Re: providing filenames dynamically
by apl (Monsignor) on Feb 24, 2009 at 13:23 UTC
Re: providing filenames dynamically
by Marshall (Canon) on Feb 24, 2009 at 15:26 UTC
    I think what you want is to process some file and replace some regex with another regex?

    If so, then consider this code.

    die "Usage $0 remove_regex replace_regex" if (@ARGV !=2); my ($remove, $replace) = @ARGV; while(<stdin>) { s/$remove/$replace/g; print; }

    @ARGV should be considered a "read only" variable like in other languages.
    Here use like: replace.pl a b <infile >outfile
    If you want to pass filenames on command line, then same idea with getting values of @ARGV, but you will have to use a open() statement to read or write them.