The Other1 wrote: > > I process a set of files and end up with a hash with server, > administrator pairs. I need to read in another file and modify (or add > if it does not exist) a line containing the word administrator following > the line with the server name. > > Hash pairs: > Server1 Bob > Server2 Chuck > Server3 Jon > > File: > server_name Server1 > location basement > administrator Wilma > OS RHEL4 > server_ip 10.0.0.5 > > server_name Server2 > location basement > administrator Fred > server_ip 10.0.0.6 > > server_name Server3 > location basement > server_ip 10.0.0.7 > > server_name Server4 > location basement > administrator Barney > server_ip 10.0.0.8 > > So I know how to change the line, I just am not sure how to search for > ONLY the line I need. I should start looking after I find the server > name and if I run into the next server definition while not finding the > line for administrator, add it. > > I thought I could do something like this: > while (<>) { > > if ($key .. /server_name/) { > > # if line exists, modify > > # else add > > } > > } > > but it doesn't seem to work as I expected. > > Also, the servers will not be in the same order in the hash and the > file, so I will need to start searching at the top of the file each > time. I know how to process a file a line at a time, but am unsure > about how to slurp entire file into RAM and process it there. > > Any pointers will be greatly appreciated! Thanks and sorry for the > lengthy post!
This problem interested me and here is my offer of an alternative solution to John's, which works in normal line input mode instead of paragraph mode. Take your pick! - The $admin variable is declared outside the loop, and is set each time a new server name is encountered. It will retain this value while processing all the records for this server, and will be undefined (and so false) if the hash defines no administrator for the server. - If we have a known administrator, then existing administrator records are discarded and location records are followed by a fabricated adminstrator record. - If there is no known administrator then all records are output unmodified. (Thanks to John for the data!) HTH, Rob use strict; use warnings; my %hash = ( Server1 => 'Bob', Server2 => 'Chuck', Server3 => 'Jon', ); my $admin; while (<DATA>) { if (/^server_name\s+(.+)/) { $admin = $hash{$1}; } if ($admin) { print unless /^administrator\s/; print "administrator $admin\n" if /^location\s/; } else { print; } } __DATA__ server_name Server1 location basement administrator Wilma OS RHEL4 server_ip 10.0.0.5 server_name Server2 location basement administrator Fred server_ip 10.0.0.6 server_name Server3 location basement server_ip 10.0.0.7 server_name Server4 location basement administrator Barney server_ip 10.0.0.8 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>