2011-10-16 27 views
1

運行這段代碼Perl中明確包名稱錯誤而需要煩惱

parsesendnotes.pl

#!/usr/bin/perl 
use strict; 
use warnings; 
use Device::SerialPort; 
use Time::HiRes qw(usleep); # For sleep in ms 

if ($#ARGV + 1 != 2) { 
    print "Usage: $0 port filename\n"; 
    print "Example: $0 /dev/ttyASM0 money.txt\n"; 
    exit 1; 
} 

my $file = $ARGV[0]; 
my $dev = $ARGV[1]; 

if (!-e $file || !-e $dev) { 
    print "File or brain not found.\n"; 
    exit 1; 
} 

my $arduino = DeviceSerialPort->new($dev); 
$arduino->baudrate(9600); 
$arduino->databits(8); 
$arduino->parity("none"); 
$arduino->stopbits(1); 

require "frequencies.pl"; 
open NOTES, "$file"; 

print $frequencies{"LA3"}; 

while (<NOTES>) { 
    chomp;  # No newline 
    s/#.*//; # No comments 
    s/^\s+//; # No leading white 
    s/\s+$//; # No trailing white 
    next unless length; 
    if ($_ =~ m/^TEMPO/) { 
     my $tempo = split(/\s+/, $_, -1); 
     print "Tempo is $tempo."; 
    } else { 
     my @tone = split(/\s+/, $_); 
    } 
    my $note = $frequencies{$tone[0]}; 
    my $duration = $tone[1]*$tempo; 
    print "Playing $tone[0] (\@$note Hz) for $tone[1] units ($duration ms)."; 
    while ($note > 255) { 
     $arduino->write(chr(255)); 
     $note -= 255; 
    } 
    $arduino->write(chr($note)); 
    $arduino->write(";"); 
    usleep($duration); 
} 

frequencies.pl

my %frequencies = (
    "PAUSE" => 0, 
    "B0" => 31, 
    "DO1" => 33, 
    "DOD1" => 35, 
    ... 
); 

我獲得這些錯誤

全局符號「%頻率」需要在./parsensendnotes2.pl線明確的包名稱30.

全局符號「%頻率」要求顯式的包名稱在./parsensendnotes2.pl線44

全局符號「 @tone」需要在./parsensendnotes2.pl行明確包名44

全局符號‘@tone’需要在./parsensendnotes2.pl行明確包名45

全局符號‘$節奏’需要明確的包名稱在./parsensendnotes2.pl行45.

全局符號「@tone」需要在./parsensendnotes2.pl行明確包名46

全局符號「@tone」需要在./parsensendnotes2.pl線46

執行明確的包名./parsensendnotes2.pl由於編譯錯誤而中止。

我在做什麼錯?

+2

「應對範圍界定」http://perl.plover.com/FAQs/Namespaces.html – tadmc

回答

4

名稱%頻率是定位於文件frequencies.pl:我會一直持續到塊結束,或者文件結束。

一個更好的辦法是刪除my和這樣做:

my %frequencies; 
eval { %frequencies = do "frequencies.pl"; } 
# must check $! and [email protected] here -- see perldoc -f do` 

然而,更好的方法是使用YAML來代替:

頻率。YML

--- 
    "PAUSE": 0 
    "B0": 31 
    "DO1": 33 
    "DOD1": 35 

然後

use YAML qw(LoadFile); 
# ... 
my $data = LoadFile("freq.yml"); 
%frequencies = %$data; 

至於@tone,$節奏&共再次my可變範圍僅限於{}塊。你應該這樣做

my $x; 
if (...) { $x = ... }; 

使$xif訪問。

1

my %frequenciesfrequencies.pl沒有內部parsesendnotes.pl聲明。

您的主腳本需要our %frequencies。當然對於其他變量也是如此。

有些文檔: