Anonyme Funktionen

 [Vorheriges Kapitel]  [Vorherige Seite]  [Inhaltsverzeichnis]  [Nächste Seite]  [Nächstes Kapitel]

cmdline2.pl
#!/usr/local/bin/perl -w

my %cmd = (
   'sum' => sub {
      my $sum = 0; foreach my $val (@_) { $sum += $val };
      print $sum, "\n";
   },
   'quit' => sub { exit 0 },
);
while (print(": "), defined(my $line = <STDIN>)) {
   my ($cmdname, @fields) = split /\s+/, $line;
   next unless defined $cmdname;
   if (defined $cmd{$cmdname}) {
      &{$cmd{$cmdname}}(@fields);
   } else {
      print "Unknown command!\n";
   }
}

*sub { ... } liefert einen Zeiger auf eine anonyme (also unbenannte) Funktion.
 
*Das erlaubt eine sehr elegante Einbettung von Funktionen in Datenstrukturen.
 

 [Vorheriges Kapitel]  [Vorherige Seite]  [Inhaltsverzeichnis]  [Nächste Seite]  [Nächstes Kapitel]
Copyright © 2000 Ingo Melzer, in HTML konvertiert am 10.11.2000