简体   繁体   中英

Replacing a part of particular lines of a file in perl

I have a file which essentially has tags in it in each of its lines. Example:

<stock_name>Abc Inc.</stock_name> <stock_value>123.456</stock_value> ........

I have a database table which has records telling (new) stock value for the stocks. The database table has say 2 columns: stock_name and stock_value

I need to scan this database table and for each stock_name in the table, I need to replace the <stock_value>xxx</stock_value> with <stock_value>yyy</stock_value> against the appropriate <stock_name> in the file (xxx=existing stock_value in the file; yyy=new stock_value retrieved from the database for the particular stock). Could anyone help me on this please?

PS: This is not a homework. I am in the middle of writing a perl script to modify the file. Appreciate your help.

If your markup is guaranteed to be <tag>value</tag> , then this will replace the values using a hash keyed off of the tag name:

my %table = (
    stock_name => 'xxx',
    stock_value => 'yyy',
);

$file = s/<([^>\/]*)>[^<]*/<$1>$table{$1}/g;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM