Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Substitution in a file 1

Status
Not open for further replies.

komark

Technical User
Sep 12, 2005
134
US
Hi,
Could anyone point me to what i'm doing wrong here. I am not able to substitute the string in the file.

#!/usr/local/bin/perl

open(ffile, "template");
while(<ffile>)
{
s/embedit/embed/;
close(ffile);
}

Thanks in advance.

 
perlfaq5 - How do I change, delete, or insert a line in a file, or append to the beginning of a file?

Code:
[url=http://perldoc.perl.org/functions/use.html][black][b]use[/b][/black][/url] [green]Tie::File[/green][red];[/red]

[black][b]use[/b][/black] [green]strict[/green][red];[/red]

[url=http://perldoc.perl.org/functions/my.html][black][b]my[/b][/black][/url] [blue]$file[/blue] = [red]'[/red][purple]template[/purple][red]'[/red][red];[/red]

[url=http://perldoc.perl.org/functions/tie.html][black][b]tie[/b][/black][/url] [black][b]my[/b][/black] [blue]@array[/blue], [red]'[/red][purple]Tie::File[/purple][red]'[/red], [blue]$file[/blue] or [url=http://perldoc.perl.org/functions/die.html][black][b]die[/b][/black][/url] [red]"[/red][purple]Can't open [blue]$file[/blue]: [blue]$![/blue][/purple][red]"[/red][red];[/red]

[olive][b]foreach[/b][/olive] [red]([/red][blue]@array[/blue][red])[/red] [red]{[/red]
	[red]s/[/red][purple]embedit[/purple][red]/[/red][purple]embed[/purple][red]/[/red][red];[/red]
[red]}[/red]

[url=http://perldoc.perl.org/functions/untie.html][black][b]untie[/b][/black][/url] [blue]@array[/blue][red];[/red]
[tt]------------------------------------------------------------
Pragmas (perl 5.10.0) used :
[ul]
[li]strict - Perl pragma to restrict unsafe constructs[/li]
[/ul]
Core (perl 5.10.0) Modules used :
[ul]
[li]Tie::File - Access the lines of a disk file via a Perl array[/li]
[/ul]
[/tt]

- Miller
 
Thanks for your post. I found this to be working as well:

open(READFILE, "<$a");
my @lines = <READFILE>;
close READFILE;
open(WRITEFILE,">$a");
foreach(@lines)
{
s/<SEARCH PATTERN>/<REPLACE PATTERN>/;
print WRITEFILE $_;
}
close WRITEFILE;
 
That would do it too :)

However, as a side note, you should avoid using variables with the name $a or $b, as they are special variables used by the sort function.

Try to get into the habit of using $x and $y instead, or even better, $filename.

- Miller
 
Thanks for the pointer.
Have a great day!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top