The Other1 wrote:
> Hi list,
Hello,
> 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 appears to do what you want:
#!/usr/bin/perl
use warnings;
use strict;
my %hash = (
Server1 => 'Bob',
Server2 => 'Chuck',
Server3 => 'Jon',
);
$/ = ''; # Paragraph mode
while ( <DATA> ) {
my ( $server ) = /^server_name\s+(.+)/m;
if ( exists $hash{ $server } ) {
s/^(administrator\s+).+/$1$hash{ $server }/m or
s/^(location.+\n)/$1administrator $hash{ $server }\n/m;
}
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
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>