asheesh has asked for the wisdom of the Perl Monks concerning the following question:

Here is my question , I am trying to search for a string within a file and replace it with another string. Below is the script that I have been working on .. Please do provide me the help .. and also one more thing I have the hash array setup .. it's the last part that's killing me is where i am trying to search and do the replace

below is my script

#!/usr/bin/perl -w # This script will process the old and new attributes # and then get a html file , grab aall the old attribute then # replace it with the new attributes $html_file = "/export/home/achhabra/example.html"; $Attribute = "/export/home/achhabra/Attributes.txt"; open (F, "$Attribute") or die ("can't open $Attribute : $!\n"); while(<F>) { chomp $_; @attributes = split(/ /, $_); $attributes_hash{$attributes[0]} = $attributes[1]; } close(F); open (H, "$html_file") or die ("can't open $html_file : $!\n"); foreach $attribute (%attributes_hash) { while(<H>) { system(":%s/\$attribute/\$attributes_hash{attribute}/g"); } } close(H);

Replies are listed 'Best First'.
Re: Hash Arrays
by chromatic (Archbishop) on Apr 16, 2003 at 20:03 UTC

    You're on the right track with the first half. The second half is confusing. You're looping through the attributes and trying to read from the file multiple times (which doesn't work -- you can't stand twice in the same stream). You're trying to execute what appears to be a vi command outside of vi.

    Try this instead. We'll build up a regex and process each line one by one:

    my $regex = qr( '(' . join('|', map { quotemeta( $_ ) } keys %attributes_hash ) . ')' ); while (<H>) { s/$regex/$attributes_hash{ $1 }/g; print; }

    That prints the output, so you'll either have to redirect it to another file internally or externally. It also doesn't handle the case of some attributes being longer than others, or being substrings of others. Throwing a sort before the map will help with that.

    Of course, if you're processing HTML files with regular expressions, the odds of false positives are not in your favor. Learning to use a module such as HTML::Parser or HTML::TokeParser would really pay off.

Re: Hash Arrays
by dragonchild (Archbishop) on Apr 16, 2003 at 19:59 UTC
    Make it like this:
    foreach $attribute (keys %attributes_hash)
    Hashes aren't arrays. To iterate over a hash, you have to create an array of keys.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.