record.txt
name: shimmer
addr: 192.168.1.11
owner: David Davis
building: main
-=-
name: bendir
addr: 192.168.1.3
owner: cindy Coltrane
building: west
-=-
name: sulawesi
addr: 192.168.1.12
owner: Ellen Monk
building: main
-=-
name: sander
addr: 192.168.1.55
owner: Alex rollins
building: east
database.pl
my $datafile = 'record.txt';
my $recordsep = "-=-\n";
open my $DATAFILE, '<', "$datafile" or die "unable to open datafile:$!\n";
{
local $/= $recordsep; #prepare to read in database file one record at a time
print "#\n# host file = GENERATED BY $o\n$ DO NOT EDIT BY HAND!\n#\n";
my %record;
while(<$DATAFILE>) {
chomp; #remove the record separator
#split into key1,value1, ....bingo, hash of record
%record = split /:\s*|\n/;
print "$record{addr}\t$record{name} $record{building} \n";
}
close $DATAFILE;
}
I have a few questions about this perl code.
{ } after the open line? local $/= $recordsep;? local vs my? What's the meaning of $o\n$ in the line
print "#\n# host file = GENERATED BY $o\n$ DO NOT EDIT BY HAND!\n#\n";
The braces define the scope where the local value of $/ is in effect. Outside the braces the variable holds its original value. Without them $/ would retain the new value up to the end of the file.
You can't use my on $/ because it is a global value. my declares a lexical value that is only in existence for the enclosing block. local is used to assign a temporary (local) value to a global value that is still accessible everywhere.
The effect those are having is to interpolate the values of variables $o and $DO into the string at that point. It looks like a mistake: DO is obviously part of the text. It's most likely that $o is the name of the originator, \n is an embedded newline and the second $ is spurious.
I imagine there is no use strict or use warnings in place on this code, and the output looks like this. No one has noticed the missing DO!
# host file = GENERATED BY originator
NOT EDIT BY HAND!
#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With