Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"my" vs "local" and the use of braces

Tags:

scope

perl

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.

  1. What's the point of having the code in braces { } after the open line?
  2. What's the point of doing local $/= $recordsep;? local vs my?
  3. 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";
    
like image 860
ealeon Avatar asked Jan 31 '26 21:01

ealeon


1 Answers

  1. 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.

  2. 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.

  3. 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!
#
like image 183
Borodin Avatar answered Feb 03 '26 16:02

Borodin