For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > March 2006 > search and replace content of file - pattern: hash









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author search and replace content of file - pattern: hash
Varga Pavol

2006-03-25, 7:57 am

Hello,
I would like to search content of file and as a pattern to use hash, but
I can't find out how to do that.

Situation:
%hash = ( "key1" => "value1",
...
"keyn" => "valuen");

open (FILE, "file.txt");
open (TMP, ">file.txt.renamed");

while (<FILE> ){
s/key1/value1/;
...
s/keyn/valuen/;
print "TMP;
}

close (FILE, TMP);

Many thanks for any help forward.
Jeff Pang

2006-03-25, 7:57 am


>Hello,
>I would like to search content of file and as a pattern to use hash, but
>I can't find out how to do that.
>
>Situation:
>%hash = ( "key1" => "value1",
> ...
> "keyn" => "valuen");
>


Hello,
Here it's easy to access the hash's value via its key,simply as:

$hash{"key1"};

I think you would want to do this replacement:

s/key1/$hash{key1}/;

About perl's hash data structure,see 'perldoc perldata' please.

--
Jeff Pang
NetEase AntiSpam Team
http://corp.netease.com
Paul Lalli

2006-03-25, 6:57 pm

Varga Pavol wrote:
> I would like to search content of file and as a pattern to use hash, but
> I can't find out how to do that.
>
> Situation:
> %hash = ( "key1" => "value1",
> ...
> "keyn" => "valuen");
>
> open (FILE, "file.txt");
> open (TMP, ">file.txt.renamed");
>
> while (<FILE> ){
> s/key1/value1/;
> ...
> s/keyn/valuen/;
> print "TMP;
> }
>
> close (FILE, TMP);


I realize this is only sample code, but it is indicative of some
programming practices that you should work on changing....
use strict and warnings
Declare your variables (which strict will force you to do)
check all open() calls to make sure they've succeeded
Use lexical filehandles rather than global barewords
Use the three-argument form of open, not the two argument form.

Now, all that being said, I think the actual answer to your question is
to loop over the keys and values of the hash using a simple while loop
and the each() operator:

#!/usr/bin/perl
use strict;
use warnings;

my %hash = (
key1 => 'value1',
key2 => 'value2',
# ...
keyn => 'valuen',
);

my $file = 'file.txt';
open my $fh, '<', $file or die "Cannot open $file: $!\n";
open my $tmp_fh, '>', "$file.renamed" or die Cannot open $file.renamed:
$!\n";

while (my $line = <$fh> ) {
while (my ($key, $value) = each %hash) {
$line =~ s/$key/$value/;
}
print $tmp_fh $line;
}

close $fh or die "Cannot close $file: $!";
close $tmp_fh or die "Cannot close $file.renamed: $!";
__END__

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com