perlopentut
perlopentut - Tutorium über das Öffnen von Sachen in Perl
BESCHREIBUNG
Perl hat zwei einfache Methoden eingebaut, um Dateien zu öffnen: der bequeme Weg über die Shell und der gewissenhafte Weg über C. Für den Weg über die Shell gibt es auch Varianten mit zwei oder drei Argumenten, die eine andere Semantik für den Umgang mit dem Dateinamen haben. Sie haben die Wahl.
Öffnen à la Shell
Perls
open -Funktion wurde so entworfen, dass sie das Verhalten der Ein- und Ausgabeumleitung in der Kommandozeile nachahmt. Hier ein paar einfache Beispiele aus der Shell:
$ meinprog datei1 datei2 datei3
$ meinprog < eingabedatei
$ meinprog > ausgabedatei
$ meinprog >> ausgabedatei
$ meinprog | anderesprog
$ anderesprog | meinprog
Und hier ein paar fortgeschrittene Beispiele:
$ anderesprog | meinprog d1 - d2
$ anderesprog 2>&1 | meinprog -
$ meinprog <&3
$ meinprog >&4
Programmierer, die Konstruktionen wie oben gewohnt sind, werden sich freuen zu erfahren, dass Perl diese bekannten Konstruke direkt unterstützt, mit fast derselben Syntax wie die Shell.
Einfaches Öffnen
Die Funktion
open erwartet zwei Argumente: Das erste ist ein Filehandle, das zweite ist ein String, der enthält was zu öffnen ist und wie es geöffnet werden soll.
open gibt wahr zurück, wenn es funktioniert; wenn es fehlschlägt, wird ein falscher Wert zurückgeliefert und die Spezialvariable
$! gesetzt, um den Systemfehler wiederzugeben. Wenn das Filehandle bereits vorher geöffnet war, wird es zuerst implizit geschlossen.
Beispiele:
open(INFO, "daten") || die("kann daten nicht öffnen: $!");
open(INFO, "< daten") || die("kann daten nicht öffnen: $!");
open(RESULTS,"> laufstat") || die("kann laufstat nicht öffnen: $!");
open(LOG, ">> logdatei") || die("kann logdatei nicht öffnen: $!");
Wenn Sie die Variante mit weniger Satzzeichen bevorzugen, können Sie es auch so schreiben:
open INFO, "< daten" or die "kann daten nicht öffnen: $!";
open RESULTS,"> laufstat" or die "kann laufstat nicht öffnen: $!";
open LOG, ">> logdatei" or die "kann logdatei nicht öffnen: $!";
Auf ein paar Sachen müssen Sie aufpassen. Erstens ist das Kleiner-als-Zeichen am Anfang optional. Wenn Sie es weglassen, geht Perl davon aus, dass Sie die Datei zum Lesen öffnen wollen.
Beachten Sie auch, dass die ersten Beispiele den logischen
|| -Operator benutzen, während darunter das
or benutzt wird, dass eine niedrigere Priorität besitzt. Würde man in den unteren Beispielen
|| benutzen, dann bedeutete es effektiv
open INFO, ("< daten" || die "kann daten nicht öffnen: $!");
was sicher nicht das ist, was Sie wollten.
Als zweites sollten Sie beachten, dass Whitespace vor oder nach dem Dateinamen ignoriert wird, wie in der Shell. Das ist gut, denn Sie wollten wohl nicht, dass diese drei Zeilen unterschiedliche Bedeutung hätten:
open INFO, "<daten"
open INFO, "< daten"
open INFO, "< daten"
Dass umgebender Whitespace ignoriert wird ist auch nützlich, wenn ein Dateiname aus einer anderen Datei eingelesen wird, ohne ihn vor dem Öffnen zu stutzen:
$dateiname = <INFO>; # ups, das \n ist noch drin
open(EXTRA, "< $dateiname) || die "kann $dateiname nicht öffnen: #!";
Das ist kein Bug, sondern ein Feature.
open imitiert die Shell dabei, wie man mit den Umleitungspfeilen festlegt, auf welche Weise eine Datei geöffnet werden soll. Das macht es genauso auch in Bezug auf den Umgang mit Whitespace um den Dateinamen. Um auf Dateien mit unartigen Namen zuzugreifen, schauen Sie unter
Die magischen Nebel vertreiben -- "Dispelling the Dweomer" nach.
Es gibt auch eine FOrm von
open mit drei Argumenten. Damit kann man die speziellen Zeichen zur Umleitung in ein eigenes Argument verlagern:
open(INFO, ">", $datei) || die "kann $datei nicht anlegen: $!";
In diesem Fall ist der Name der zu öffnenden Datei genau das, was in
$datei drin steht, und Sie müssen sich nicht darum kümmern, ob
$datei irgendwelche Zeichen enthält, die die Art des Öffnens beeinflussen, oder ob der Dateiname mit Whitespace anfängt, der in der zweiparametrigen Form verschluckt würde. Auch ist es immer eine gute Sache, wenn unnötige String-Interpolation vermieden wird.
Indirekte Filehandle
Das erste Argument zu
open kann eine Referenz auf ein Filehandle sein. Seit perl 5.6.0 erzeugt Perl automatisch ein Filehandle und legt eine Referenz darauf in das erste Argument, falls dieses nicht initialisiert ist. Das geht so:
open( my $in, $inputdatei ) or die "kann $inputdatei nicht lesen: $!";
while ( <$in> ) {
# mach was mit $_
}
close $in;
Indirekte Filehandle machen das Namensraum-Management einfacher. Da Filehandles im aktuellen Package global sind, gibt es einen Konflikt, wenn zwei Subroutinen
INFILE öffnen wollen. Wenn zwei Funktionen dagegen indirekte Filehandles wie
my $infile öffnen, gibt es weder jetzt noch zukünftig einen Konflikt.
Ein anderer angenehmer Vorteil ist, dass indirekte Filehandle automatisch geschlossen werden, wenn ihr Geltungsbereich verlassen wird oder sie undef werden:
sub erstezeile {
open( my $in, shift ) && return scalar <$in>;
# kein close() erforderlich
}
Öffnen von Pipes
Wenn man in C eine Datei mit der Standard-I/O-Bibliothek öffnen möchte, nutzt man die Funktion
fopen , wenn man aber eine Pipe öffnen möchte, nutzt man die Funktion
popen . In der Shell dagegen benutzt man einfach ein anderes Zeichen zur Umleitung. So ist es auch in Perl. Der
open -Aufruf bleibt der gleiche, nur die Argumente sind andere.
Wenn das erste Zeichen ein Pipe-Symbol ist, dann führt
open einen neuen Befehl aus und öffnet ein Filehandle mit nur-schreibendem Zugriff zu diesem Befehl. Damit kann man in dieses Handle schreiben, und alles, was man hineinschreibt, erscheint an der Standardeingabe des Befehls. Ein Beispiel:
open(DRUCKER, "| lpr -Plp1") || die "kann lpr nicht starten: $!";
print DRUCKER "zeug\n";
close(DRUCKER) || die "kann lpr nicht schließen: $!";
Wenn das letzte Zeichen ein Pipe-Symbol ist, dann startet man einen neuen Befehl und öffnet ein Filehandle mit nur-lesendem Zugriff, das aus diesem Befehl führt. Damit bekommt man alle Ausgaben, die der Befehl auf seine Standardausgabe schreibt, zum Lesen auf dieses Filehandle. Beispiel:
open(NETZ, "netstat -i -n |") || die "kann netstat nicht forken: $!";
while (<NET>) { } # mach etwas mit der Ausgabe von netstat
close(NET) || die "kann netstat nicht schließen: $!";
Was passiert, wenn man versucht, eine Pipe zu oder von einem nicht vorhandenen Befehl zu öffnen? Wenn möglich wird Perl den Fehlschlag entdecken und wie üblich
$! setzen. Aber wenn der Befehl spezielle Shell-Sonderzeichen wie
> oder
* enthält, sogenannte 'Metazeichen', dann führt Perl den Befehl nicht direkt aus, sondern startet eine Shell, die dann den Befehl ausführt. Damit bekommt nur die Shell den Fehler mit. In diesem Fall liefert
open nur dann einen Fehler, wenn Perl nicht mal die Shell aufrufen kann. Unter L<perlfaq8/"Wie kann ich STDERR von einem externen Befehl einlesen?"> erfahren Sie, was man in diesem Fall machen kann. Es gibt auch eine Erläuterung dazu in
perlipc.
Wenn Sie eine bidirektionale Pipe öffnen möchten, hilft Ihnen das Modul IPC::Open2 dabei. Mehr dazu unter
perlipc, Bidirektionale Kommunikation mit einem anderen Prozess.
Die Minus-Datei
Wieder auf den Pfaden der Standard-Shell-Utilities wandelnd behandelt die
open -Funktion in Perl eine Datei anders, wenn deren Namen ein einfaches Minuszeichen ("-") ist. Wenn man Minus zum Lesen öffnet, greift man in Wirklichkeit auf die Standardeingabe zu. Wenn man Minus zum Schreiben öffnet, ist es tatsächlich die Standardausgabe.
Wenn man Minus als Default für Ein- oder Ausgabe nutzen kann, was passiert dann, wenn man eine Pipe nach oder von Minus öffnet? Was für einen Default-Befehl würde dann aufgerufen? Genau das Skript, das gerade läuft! Es handelt sich eigentlich um ein verstecktes
fork in einem
open -Aufruf. Mehr Details dazu finden sich unter
perlipc, Sicheres Open mit Pipes.
Gemischtes Lesen und Schreiben
Es ist möglich, gleichzeitigen Lese- und Schreibzugriff anzugeben. Man muss dafür einzig ein "+"-Zeichen vor der Umleitung angeben. Aber wie in der Shell gilt: ein Kleiner-als-Zeichen bei einem Dateinamen erzeugt niemals eine neue Datei, es öffnet nur eine bestehende. Auf der anderen Seite wird eine bestehende Datei immer gelöscht (auf die Länge Null gekürzt) oder eine brandneue Datei angelegt, falls noch keine existiert, wenn man ein Größer-als-Zeichen benutzt. Ein zusätzliches "+" macht keinen Unterschied dabei, ob es entweder nur für existierende Dateien funktioniert oder existierende löscht.
open(WTMP, "+< /usr/adm/wtmp")
|| die "kann /usr/adm/wtmp nicht öffnen: $!";
open(SCREEN, "+> lkscreen")
|| die "kann lkscreen nicht öffnen: $!";
open(LOGFILE, "+>> /var/log/proglog"
|| die "kann /var/log/proglog nicht öffnen: $!";
Im ersten Beispiel wird nie eine neue Datei anlegen, im zweiten wird eine bestehende immer gelöscht. Im dritten Beispiel wird, wenn nötig, eine neue Datei angelegt und eine bestehende nicht gelöscht; es ist auch möglich, an jeder Stelle der Datei zu lesen, aber es kann nur ans Ende geschrieben werden. Kurz gesagt, der erste Fall ist wesentlich häufiger als der zweite und dritte, welche fast immer falsch sind. (Wenn Sie C kennen: Das Plus in Perls
open stammt historisch aus der C-Funktion fopen(3S), welche schlussendlich auch aufgerufen wird.)
Tatsächlich werden Sie diese Herangehensweise wahrscheinlich nicht nutzen wollen, wenn es darum geht, einen Dateiinhalt zu verändern, außer es handelt sich um eine Binärdatei, wie im Fall von WTMP oben. Stattdessen ist hier die Kommandozeilenoption
-i von Perl nützlich. Mit dem folgenden Befehl werden in allen C, C++ oder yacc Quellcode- und Headerdateien alle "foo"s durch "bar"s ersetzt. Dabei bleibt die alte Version erhalten und bekommt ein ".orig" an den Dateinamen angehängt:
$ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy]
Dies ist der kürzeste Weg für einige Umbenennungsspielchen, die wirklich die beste Möglichkeit darstellen, Textdateien zu aktualisieren. Mehr dazu bei der zweiten Frage in
perlfaq5.
Filter
Einer der häufigsten Anwendungsfälle für
open ist einer, den man nicht mal mitbekommt. Wenn Sie das Filehandle ARGV mittels
<ARGV> abarbeiten, macht Perl in Wirklichkeit ein implizites
open für jede Datei in @ARGV. Wenn man also ein Programm so aufruft
$ meinprog datei1 datei2 datei3
dann kann man mit einer Konstruktion wie der folgenden alle Dateien nacheinander öffnen und bearbeiten:
while (<>) {
# mach etwas mit $_
}
Wenn beim ersten Start der Schleife @ARGV leer ist, tut Perl so, als ob man Minus geöffnet hätte, also die Standardeingabe. Tatsächlich wird sogar $ARGV, der Name der momentan geöffneten Datei bei der Verarbeitung von
<ARGV> , unter diesen Umständen auf "-" gesetzt.
Sie können auch gerne @ARGV vor dem Start der Schleife an Ihre Bedürfnisse anpassen. Ein Grund dafür könnte sein, dass Sie Kommandozeilenoptionen, die mit einem Minus beginnen, entfernen wollen. Einfache Fälle kann man von Hand lösen, aber die Getopts-Module bieten sich da an:
use Getopt::Std;
# -v, -D, -o ARG setzen $opt_v, $opt_D, $opt_o
getopts("vDo:");
# -v, -D, -O ARG setzen $args{v}, $args{D}, $args{o}
getopts("vDo:", \%args);
Oder auch das Standardmodul Getopt::Long, bei dem benannte Argumente möglich sind:
use Getopt::Long;
GetOptions( "verbose" => \$verbose, # --verbose
"Debug" => \$debug, # --Debug
"output=s" => \$output ); # --output=irgendwas oder --output irgendwas
Man kann die Argumentliste auch bearbeiten, um bei einer leeren Liste als Default alle Dateien zu nehmen:
@ARGV = glob("*") unless @ARGV;
Man kann auch alle Dateien außer reinen Textdateien herausfiltern. Damit das nicht so stillschweigend geschieht, könnte man die Dateien bei der Verarbeitung nennen.
@ARGV = grep { -f && -T } @ARGV;
Wenn man die Kommandozeilenoptionen
-n oder
-p benutzt, sollte man Änderungen an @ARGV innerhalb eines
BEGIN{} -Blocks vornehmen.
Denken Sie daran, dass ein normales
open besondere Eigenschaften hat. Es kann fopen(3S) oder popen(3S) aufrufen, je nachdem, wie seine Argumente aussehen; daher wird es manchmal auch "magisches open" genannt. Hier ein Beispiel:
$pwdinfo = `domainname` =~ /^(\(none\))?$/
? '< /etc/passwd'
: 'ypcat passwd |';
open(PWD, $pwdinfo)
or die "kann $pwdinfo nicht öffnen: $!";
Dieses Verhalten kommt auch bei der Filterverarbeitung ins Spiel. Da die Verarbeitung von
<ARGV> das ganz normale, Shell-artige
open von Perl benutzt, berücksichtigt es auch all die speziellen Sachen, die wir gerade gesehen haben:
$ meinprog d1 "cmd1|" - d2 "cmd2|" d3 < tmpfile
Dieses Programm liest erst von Datei
d1 , dann dem Prozess
cmd1 , der Standardeingabe (in diesem Fall
tmpfile ), dann der Datei
d2 , dem Befehl
cmd2 und schließlich der Datei
d3 .
Ja, das heißt auch, dass Sie eine Datei namens "-" (oder ähnliches), die Sie in Ihrem Verzeichnis haben, nicht einfach so mit Namen an
open übergeben können. Sie müssen sie als "./-" angeben, genauso, wie Sie es bei Programm
rm machen würden. Alternativ können Sie auch
sysopen benutzen, das weiter unten erklärt wird.
Eine der nützlicheren Anwendungen ist das Abändern von Dateien mit einem bestimmten Namen in Pipes. Beispielsweise um mit
gzip oder
compress komprimierte Dateien automatisch mit
gzip auszupacken:
@ARGV = map { /\.(gz|Z)$/ ? "gzip -dc $_ |" : $_ } @ARGV;
Oder, wenn Sie das Programm
GET aus dem LWP-Paket installiert haben, können Sie vor der Verarbeitung Inhalte aus URLs herunterladen:
@ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV;
<ARGV> wird eben nicht ohne Grund magisch genannt. Ziemlich raffiniert, oder?
Öffnen à la C
Wenn man es bequem wie auf der Shell mag, ist Perls
open definitiv die richtige Wahl. Wenn man andererseits mehr Präzision haben möchte, als C's einfaches fopen(3S) bietet, dann sollte man einen Blick auf Perls
sysopen werfen, welches eine direkte Schnittstelle zum Systemaufruf open(2) ist. Das heißt auch, dass es etwas komplizierter ist, aber das ist der Preis für mehr Präzision.
sysopen erwartet drei (oder vier) Argumente.
sysopen HANDLE, PFAD, FLAGS, [MASKE]
Das Argument HANDLE ist ein Filehandle wie bei
open . PATH ist direkt eine Pfadangabe, ohne Berücksichtigung von Kleiner-als- oder Größer-als-Zeichen, Pipes oder Minuszeichen. Auch wird Whitespace nicht ignoriert. Wenn Whitespace da steht, ist er Bestandteil des Pfads. Das Argument FLAGS enthält einen oder mehr Werte, die aus dem Fcntl-Modul stammen und mit bitweisem Oder ('|') verknüpft werden. Das letzte Argument, die MASKE, ist optional; wenn es benutzt wird, wird es mit der aktuellen
umask des Benutzers kombiniert, um den Mode für das Anlegen der Datei festzulegen. Meistens sollte man es weglassen.
Obwohl für Nur-Lese-Zugriff (read-only), Nur-Schreib-Zugriff (write-only) und Lese-Schreib-Zugriff (read-write) die Werte für FLAGS üblicherweise 0, 1 und 2 sind, gilt dies nicht auf allen Systemen. Stattdessen sollte man am besten die gewünschten Konstanten aus dem Fcntl-Modul importieren. Die folgenden Standard-Flags sind definiert:
O_RDONLY Nur-Lese-Zugriff (Read only)
O_WRONLY Nur-Schreib-Zugriff (Write only)
O_RDWR Lese-Schreib-Zugriff (Read and write)
O_CREAT Datei anlegen, wenn sie nicht schon existiert
O_EXCL Fehler, wenn die Datei schon existiert
O_APPEND An Datei anhängen
O_TRUNC Datei abschneiden (Truncate)
O_NONBLOCK Nicht-blockierender Zugriff
Weniger gebräuchliche Flags, die manchmal auf einigen Betriebssystemen zur Verfügung stehen sind unter anderem
O_BINARY ,
O_TEXT ,
O_SHLOCK ,
O_EXLOCK ,
O_DEFER ,
O_SYNC ,
O_ASYNC ,
O_DSYNC ,
O_RSYNC ,
O_NOCTTY ,
O_NDELAY und
O_LARGEFILE . Schlagen Sie in Ihrer Manpage zu open(2) oder der lokalen Entsprechung dazu nach, wenn Sie mehr wissen möchten. (Anmerkung: Seit Perl 5.6 wird das Flag
O_LARGEFILE , sofern verfügbar, automatisch zu den sysopen()-Flags hinzugefügt, da die Unterstützung von großen Dateien der Default ist.)
Hier eine Anleitung, wie man
sysopen benutzt, um die einfachen
open -Aufrufe zu emulieren, die wir vorher gezeigt haben. Wir verzichten auf das
|| die $! , um die Beispiele einfacher zu halten, aber Sie sollten sicher stellen, dass Sie in echtem Code immer den Rückgabewert prüfen. Das Verhalten ist nicht das gleiche, da
open führenden und anhängenden Whitespace entfernt, aber das Konzept sollte klar sein.
Eine Datei zum Lesen öffnen:
open(FH, "< $pfad");
sysopen(FH, $pfad, O_RDONLY);
Eine Datei zum Schreiben öffnen; dabei die Datei neu anlegen, wenn nötig, und eine vorhandene Datei auf Länge Null kürzen:
open(FH, "> $pfad");
sysopen(FH, $pfad, O_WRONLY | O_TRUNC | O_CREAT);
Eine Datei zum Anhängen öffnen, dabei neu anlegen, wenn nötig:
open(FH, ">> $pfad");
sysopen(FH, $pfad, O_WRONLY | O_APPEND | O_CREAT);
Eine Datei zum Aktualisieren öffnen, wobei die Datei bereits existieren muss:
open(FH, "+< $pfad");
sysopen(FH, $pfad, O_RDWR);
Und hier noch ein paar Sachen, die man mit
sysopen machen kann, aber nicht mit einem normalen
open . Wie man sieht, kommt es nur darauf an, die Flags im dritten Argument richtig auszuwählen.
Eine Datei zum Schreiben öffnen, dabei eine Datei neu anlegen, die vorher nicht existieren darf:
sysopen(FH, $pfad, O_WRONLY | O_EXCL | O_CREAT);
Eine Datei zum Anhängen öffnen, wobei die Datei schon vorher existieren muss:
sysopen(FH, $path, O_WRONLY | O_APPEND);
Eine Datei zum Aktualisieren öffnen, wobei die Datei wenn nötig neu angelegt wird:
sysopen(FH, $path, O_RDWR | O_CREAT);
Eine Datei zum Aktualisieren öffnen, wobei die Datei vorher noch nicht existieren darf:
sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT);
Eine Datei mit nicht-blockierendem Zugriff öffnen, wobei die Datei wenn nötig neu angelegt wird:
sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT);
Die neuesten Moden für Zugriffsrechte
Wenn man die Argument MASKE von
sysopen weglässt, benutzt Perl den oktalen Wert 0666. Die normale MASKE für ausführbare Dateien und Verzeichnisse sollte 0777 sein, für alles andere 0666.
Warum so freizügig? Nun, eigentlich ist es das gar nicht. Die MASKE wird durch die
umask des aktuellen Prozesses verändert. Eine umask ist eine Zahl, die die Bits für die
nicht erlaubten Zugriffsrechte darstellt, d.h. Bits, die im Feld für die Zugriffsrechte einer Datei nicht aktiviert werden.
Wenn zum Beispiel die
umask 027 ist, dann würde der Teil 020 die Schreibberechtigung für Gruppen wegnehmen und der Teil 007 die Lese-, Schreib- und Ausführungsberechtigungen für andere. Unter dieser Bedingung würde eine MASKE von 0666, die an
sysopen übergeben wird, bedeuten, dass eine Datei mit den Zugriffsrechten 0640 angelegt würde, denn
0666 & ~027 ergibt 0640.
Die sollten das MASKE-Argument von
sysopen nur selten nutzen. Es schränkt die Wahlfreiheit des Benutzers ein, welche Zugriffsrechte neue Dateien haben sollen. Jemandem die Wahl zu nehmen ist fast immer eine schlechte Idee. Eine Ausnahme wäre, wenn sensible oder private Daten gespeichert werden sollen, wie bei E-Mail-Ordnern, Cookie-Dateien oder internen temporären Dateien.
Obskure Open-Tricks
Dateien mehrfach öffnen (dups)
Manchmal hat man bereits ein offenes Filehandle und möchte ein weiteres Handle haben, dass ein Duplikat des ersten ist. In der Shell setzen wir ein kaufmännisches Und (
& ) vor einen Dateideskriptor, wenn wir Umleitungen anlegen. Beispielsweise wird durch
2>&1 der Deskriptor 2 (in Perl ist das STDERR) auf den Deskriptor 1 (der in Perl normalerweise STDOUT ist) umgeleitet. In Perl ist das eigentlich genauso: Ein Dateiname, der ein kaufmännisches Und am Anfang hat, wird wie ein Dateideskriptor behandelt, wenn es sich um eine Zahl handelt, oder wie ein Filehandle, wenn es sich um einen String handelt:
open(SAVEOUT, ">&SAVEERR") || die "kann SAVEERR nicht duplizieren: $!";
open(MHCONTEXT, "<&4") || die "kann fd4 nicht duplizieren: $!";
Wenn eine Funktion also einen Dateinamen erwartet, man ihr aber keinen Dateinamen übergeben will, weil man die Datei schon offen hat, kann man ihr einfach ein Filehandle mit einem führenden "
& " übergeben. Es ist allerdings besser, wenn man das Filehandle voll qualifiziert angibt, falls die Funktion sich in einem anderen Package befindet:
einefunktion("&main::LOGDATEI");
Wenn einefunktion() vor hat, das Argument zu öffnen, kann es auf diese Weise das bereits offene Filehandle benutzen. Das ist etwas anderes, als ein Filehandle zu übergeben, denn mit dem Filehandle kann man keine Datei öffnen. Hier hat man etwas, dass man an open() übergeben kann.
Wenn man eines dieser trickreichen, neumodischen I/O-Objekte hat, auf das die C++-Leute so abfahren, dann klappt dieser Trick nicht, da es sich nicht um ein ordentliches natives Filehandle im Sinne von Perl handelt. Man muss fileno() benutzen, um die zugehörige Deskriptorzahl herauszufinden, vorausgesetzt es besteht die Möglichkeit dazu:
use IO::Socket;
$handle = IO::Socket::INET->new("www.perl-community.de:80");
$fd = $handle->fileno;
einefunktion("&$fd"); # das ist kein indirekter Funktionsaufruf
Es kann aber einfacher (und auf jeden Fall schneller) sein, wenn man echte Filehandles benutzt:
use IO::Socket;
local *REMOTE = IO::Socket::INET->new("www.perl-community.de:80");
die "kann nicht verbinden" unless defined(fileno(REMOTE));
einefunktion("&main::REMOTE");
Wenn vor dem Filehandle oder der Deskriptorzahl nicht ein einfaches "&", sondern die Kombination "&=" steht, dann legt Perl nicht einen vollständig neuen Deskriptor an, der mit dem Systemaufruf dup(2) auf das gleiche Ziel zeigt. Stattdessen legt es mit dem Bibliotheksaufruf fdopen(3S) nur eine Art Alias auf den bestehenden Deskriptor an. Das ist leicht sparsamer von Verbrauch der Systemressourcen her, was aber heutzutage selten von Bedeutung ist. Hier ein Beispiel:
$fd = $ENV{"MHCONTEXTFD"};
open(MHCONTEXT, "<&=$fd") or die "fdopen $fd geht nicht: $!";
Wenn man das magische
<ARGV> benutzt, dann könnte man als Kommandozeilenargument sogar etwas wie
"<&=$MHCONTEXTFD" in @ARGV einfügen, aber wir haben bisher noch niemanden gesehen, der so etwas tatsächlich macht.
Den Zauber bannen - "Dispelling the Dweomer"
Perl ist mehr eine DWIM-Sprache als zum Beispiel Java. Dabei ist DWIM eine Abkürzung für "do what I mean" -- mach, was ich will. Aber dieses Prinzip führt manchmal zu mehr verborgener Magie als man brauchen kann. Auf diese Weise ist Perl auch mit
dweomer gefüllt, ein obskures Wort, das so etwas wie
Verzauberung bedeutet. Manchmal ist Perls "DWIMmer" einfach zu sehr "dweomer", als dass es noch wirklich hilfreich wäre.
Wenn einem das magische
open etwas zu magisch ist, muss man trotzdem nicht gleich zu
sysopen greifen. Um eine Datei mit beliebig seltsamen Zeichen im Namen zu öffnen, muss man den führenden und anhängenden Whitespace schützen. Führender Whitespace in einem Dateinamen wird geschützt, indem man ein
"./" davor setzt. Anhängender Whitespace wird geschützt, indem man ein ASCII-Nullbyte (
"\0" ) an das Ende des Strings setzt.
$datei =~ s#^(\s)#./$1#;
open (FH, "< $datei\0") || die "kann $datei nicht öffnen: $!";
Das setzt natürlich voraus, dass im System der Punkt für das aktuelle Verzeichnis steht, der Schrägstrich der Verzeichnistrenner ist, und ASCII-Nullbytes in einem Dateinamen nicht erlaubt sind. Die meisten Betriebssysteme folgen diesen Konventionen, darunter aller POSIX- und alle Microsoft-Systeme. Das einzige noch halbwegs weit verbreitete System, das anders arbeitet, ist der "Classic"-Betriessystem für Macintosh, welches einen Doppelpunkt benutzt, wo jeder sonst einen Schrägstrich einsetzt. Vielleicht ist
sysopen doch keine so schlechte Wahl.
# "Sam setzte sich auf die Erde und legte den Kopf in die Hände.
# »Ich wünschte, ich wäre nie hierher gekommen, und ich will auch
# keinen Zauber mehr sehen«, sagte er und schwieg dann."
for (@ARGV) {
s#^([^./])#./$1#;
$_ .= "\0";
}
while (<>) {
# jetzt $_ verarbeiten
}
Seien Sie aber gewarnt: Anwender sind wahrscheinlich nicht begeistert, wenn sie kein "-" für Standardeingabe verwenden können, wie es Konvention ist.
Pfadnamen als Handles
Es ist Ihnen vielleicht aufgefallen, dass die Funktionen
warn und
die in Perl Meldungen der folgenden Art erzeugen können:
Irgendeine Warnung at skriptname line 29, <FH> line 7.
Die Meldung erscheint so, weil Sie ein Filehandle FH geöffnet und sieben Datensätze davon gelesen haben. Aber wie kommt man an den Name der Datei statt des Handles?
Wenn man das Programm nicht mit
strict refs ausführt, oder wenn man dieses Pragma vorübergehend abschaltet, dann braucht man nur folgendes zu machen:
open($pfad, "< $pfad") || die "kann $pfad nicht öffnen: $!";
while (<$pfad>) {
# was auch immer
}
Wenn man den Pfadnamen der Datei als Handle benutzt, sehen Meldungen eher so aus:
Irgendeine Warnung at skriptname line 29, </etc/motd> line 7.
Open mit nur einem Argument
Erinnern Sie sich noch, dass wir gesagt haben, Perls open() bekommt zwei Argumente? Da haben wir nicht ganz die Wahrheit gesagt. Eigentlich kommt es auch mit nur einem Argument zurecht. Genau dann, wenn es sich um eine globale (und nicht lexikalische) Variable handelt, kann man
open ein einzelnes Argument übergeben, nämlich das Filehandle. Den Pfad holt es sich dann aus der globalen skalaren Variablen mit dem gleichen Namen.
$DATEI = "/etc/motd";
open DATEI or die "kann $DATEI nicht öffnen: $!";
while (<DATEI>) {
# was auch immer
}
Warum gibt es so etwas überhaupt? Eigentlich nur aus historischen Gründen. Es ist schon von Anbeginn in Perl enthalten - wenn nicht länger.
Mit STDIN und STDOUT herumspielen
Es ist eine gute Idee, am Ende des Programms STDOUT explizit zu schließen:
END { close (STDOUT) || die "kann STDOUT nicht schließen: $!" }
Wenn man das nicht macht, und das Programm schreibt aufgrund einer Kommandozeilenumleitung die Partition voll, dann erhält man keine Fehlermeldung beim Abbruch.
Man muss STDIN und STDOUT auch nicht so hinnehmen, wie sie übergeben werden. Sie können ohne weiteres neu geöffnet werden.
open(STDIN, "< datei")
|| die "kann datei nicht öffnen: $!";
open (STDOUT, "> ausgabe")
|| die "kann ausgabe nicht öffnen: $!";
Auf die neue Standardein- und -ausgabe kann sofort zugegriffen werden, und man kann sie an Unterprozesse weitergeben. Es hat den gleichen Effekt, als wäre das Programm direkt mit diesen Umleitungen auf der Kommandozeile aufgerufen worden.
Wahrscheinlich ist es aber interessanter, sie mit Pipes zu verbinden. Hier ein Beispiel:
$pager = $ENV{PAGER} || "(less || more)";
open (STDOUT, "| $pager")
|| die "kann keine Pipe zur seitenweisen Ausgabe forken: $!"
Damit sieht es so aus, als wäre das Programm direkt in einer Pipe aufgerufen worden, in der STDOUT in ein Pagerprogramm umgeleitet wird. Man kann diese Umleitung auch in Verbindung mit einem impliziten Fork des eigenen Prozesses nutzen. Das kann nützlich sein, wenn man die Weiterverarbeitung im eigenen Programm, aber in einem separaten Prozess vornehmen möchte:
head(100);
while (<>) {
print;
}
sub head {
my $zeilen = shift || 20;
return if $pid = open(STDOUT, "|-"); # Parent kehrt zurück
die "kann nicht forken: $!" unless defined $pid;
while (<STDIN>) {
last if --$zeilen < 0;
print;
}
exit;
}
Auf diese Weise kann man nacheinander beliebig viele Ausgabefilter in seinen Ausgabestream schieben.
Andere I/O-Fragen
Die hier behandelten Themen betreffen eigentlich nicht die Argumente von
open oder
sysopen , aber es geht um das, was man mit seinen offenen Dateien macht.
Dateien öffnen, die keine Dateien sind
Wann ist eine Datei keine Datei? Man könnte sagen, wenn sie existiert, aber keine gewöhnliche Datei ("plain file") ist. Wir prüfen vorsichtshalber zuerst, ob sie ein symbolischer Link ist.
if (-l $datei) || ! -f _) {
print "$datei ist keine gewöhnliche Datei\n";
}
Was für Dateien gibt es denn noch, außer, naja, eben Dateien? Verzeichnisse, symbolische Links, benannte Pipes, Unix-Sockets, und Block- und Zeichorientierte Geräte. Auch das sind alles Dateien, aber keine
gewöhnlichen Dateien. Das hat aber nichts mit Textdateien zu tun. Nicht alle Textdateien sind gewöhnliche Dateien. Nicht alle gewöhnlichen Dateien sind Textdateien. Deshalb gibt es eigene Filetests für
-f und
-T .
Um ein Verzeichnis zu öffnen, sollte man die Funktion
opendir benutzen, und es dann mit
readdir verarbeiten. Dabei sollte man sorgfältig darauf achten, wenn nötig den Verzeichnisnamen wieder einzusetzen:
opendir(DIR, $dirname) or die "kann Verzeichnis $dirname nicht öffnen: $!";
while (defined($datei = readdir(DIR))) {
# mach etwas mit "$dirname/$datei"
}
closedir(DIR);
Wenn man Verzeichnisse rekursiv verarbeiten möchte, sollte man besser das Modul
File::Find benutzen. Dies hier gibt zum Beispiel rekursiv alle Dateien aus und setzt einen Schrägstrich ans Ende des Namens, wenn es sich um ein Verzeichnis handelt.
@ARGV = qw(.) unless @ARGV;
use File::Find;
find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;
Das hier findet alle defekten Symbolischen Links unter einem bestimmten Verzeichnis:
find sub { print "$File::Find::name\n" if -l && !-e }, $dir;
Wie Sie sehen, kann man bei einem symbolischen Link einfach so tun, als wäre er das, worauf er zeigt. Wenn man aber genau wissen möchte,
worauf er zeigt, dann ist
readlink das Richtige:
if (-l $datei) {
if (defined($wohin = readlink($datei))) {
print "$datei zeigt auf $wohin\n";
} else {
print "$datei zeigt nirgendwo hin: $!\n";
}
}
Benannte Pipes öffnen
Benannte Pipes sind etwas vollkommen anderes. Man tut so, als wären es normale Dateien, aber das Öffnen blockiert normalerweise bis es sowohl einen lesenden wie einen schreibenden Prozess gibt. Mehr dazu kann man in
perlipc, Benannte Pipes nachlesen. Unix-artige Sockets sind wiederum eine andere Spezies; sie sind in
perlipc, Unix-artige TCP-Clients und -Server beschrieben.
Das Öffnen von Gerätedateien kann ganz einfach, aber auch knifflig sein. Nehmen wir an, Sie wissen, was Sie tun, wenn Sie ein Blockdevice öffnen. Zeichenorientierte Geräte sind interessanter. Sie werden typischerweise für Modems, Mäuse oder einige Arten von Druckern benutzt. Das wird in L<perlfaq8/"Wie kann ich den seriellen Port lesen und beschreiben?"> beschrieben. Meist reicht es aus, sie behutsam zu öffnen:
sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)
# (O_NOCTTY wird auf POSIX-System nicht mehr benötigt)
or die "kann /dev/ttyS1 nicht öffnen: $!";
open(TTYOUT, "+>&TTYIN")
or die "kann TTYIN nicht duplizieren: $!";
$ofh = select(TTYOUT); $| = 1; select($ofh);
print TTYOUT "+++at\015";
$answer = <TTYIN>;
Deskriptoren, die nicht mit
sysopen geöffnet wurden, wie zum Beispiel Sockets, kann man mit
fcntl auf nicht-blockierenden Zugriff setzen:
use Fcntl;
my $alte_flags = fcntl($handle, F_GETFL, 0)
or die "kann Flags nicht bekommen: $!";
fcntl($handle, F_SETFL, $alte_flags | O_NONBLOCK)
or die "nicht-blockierender Zugriff lässt sich nicht setzen: $!";
Wenn man TTYs manipulieren muss, ist es am Besten, extern das Programm stty(1) aufzurufen oder das portable POSIX-Interface zu benutzen, statt in einem Morast aus verschlungenen, sich windenden, immer wieder anderen
ioctl s unterzugehen. Für den richtigen Durchblick muss man erst die Manpage zu termios(3) lesen, die das POSIX-Interface zu TTY-Devices beschreibt, und anschließend
POSIX, in dem das Perl-Interface zu POSIX beschrieben ist. Es gibt auf CPAN auch einige High-Level-Module, die bei solchen Spielereien helfen können. Schauen Sie sich mal Term::ReadKey und Term::ReadLine an.
Sockets öffnen
Was kann man sonst noch öffnen? Für eine Socketverbindung wird man jedenfalls keine der beiden open-Funktionen in Perl nehmen. Mehr dazu in
perlipc, Sockets: Client-Server-Kommunikation. Hier ist ein Beispiel. Sobald FH definiert ist, kann man es als bidirektionales Filehandle benutzen.
use IO::Socket;
local *FH = IO::Socket::INET->new("www.perl-community.de:80");
Um eine URL zu öffnen, sind die LWP-Module vom CPAN das, was der Doktor einem rät. Es gibt keine Filehandle-Interface, aber es ist ganz einfach, an den Inhalt eines Dokuments zu kommen:
use LWP::Simple;
$doc = get('http://www.linpro.no/lwp/');
Binärdateien
Bestimmte veraltete Systeme haben ein I/O-Modell, das man wohlwollend unheilbar verworren nennen könnte (manche nennen es einfach kaputt). Dort ist eine Datei gar keine Datei - zumindest nicht, was die Standard-C-Library angeht.
######
Locking von Dateien
######
PerlIO-Layer
######
"SIEHE AUCH"
Die Funktionen
open und
sysopen in perlfunc(1). Die Manpages zu den Systemcalls open(2), dup(2), fopen(3) und fdopen(3). Die POSIX-Dokumentation.
"AUTOR und COPYRIGHT"
Copyright 1998 Tom Christiansen.
Diese Dokumentation ist frei; Sie können sie unter den gleichen Bedingungen wie Perl selbst weiter verbreiten und/oder verändern.
Unabhängig von der Art der Verbreitung werden hiermit alle Codebeispiele der Public Domain übergeben. Es ist Ihnen erlaubt und erwünscht, dass Sie diesen Code nach Wunsch für Ihren Spaß oder Ihren Gewinn in eigenen Programmen nutzen. Ein einfacher Kommentar im Code, in dem Sie mir Anerkennung zollen, wäre guter Ton, ist aber nicht erforderlich.
GESCHICHTE
Erstes Release: Sat Jan 9 08:09:11 MST 1999
"ÜBERSETZUNG"
Copyright 2008 Harald Bongartz <harald {at} perlwiki.de>.
Diese Übersetzung unterliegt den gleichen Rechten wie das Original.
Originalfassung
NAME
perlopentut - tutorial on opening things in Perl
DESCRIPTION
Perl has two simple, built-in ways to open files: the shell way for convenience, and the C way for precision. The choice is yours.
Open à la shell
Perl's
open function was designed to mimic the way command-line redirection in the shell works. Here are some basic examples from the shell:
$ myprogram file1 file2 file3
$ myprogram < inputfile
$ myprogram > outputfile
$ myprogram >> outputfile
$ myprogram | otherprogram
$ otherprogram | myprogram
And here are some more advanced examples:
$ otherprogram | myprogram f1 - f2
$ otherprogram 2>&1 | myprogram -
$ myprogram <&3
$ myprogram >&4
Programmers accustomed to constructs like those above can take comfort in learning that Perl directly supports these familiar constructs using virtually the same syntax as the shell.
Simple Opens
The
open function takes two arguments: the first is a filehandle, and the second is a single string comprising both what to open and how to open it.
open returns true when it works, and when it fails, returns a false value and sets the special variable $! to reflect the system error. If the filehandle was previously opened, it will be implicitly closed first.
For example:
open(INFO, "datafile") || die("can't open datafile: $!");
open(INFO, "< datafile") || die("can't open datafile: $!");
open(RESULTS,"> runstats") || die("can't open runstats: $!");
open(LOG, ">> logfile ") || die("can't open logfile: $!");
If you prefer the low-punctuation version, you could write that this way:
open INFO, "< datafile" or die "can't open datafile: $!";
open RESULTS,"> runstats" or die "can't open runstats: $!";
open LOG, ">> logfile " or die "can't open logfile: $!";
A few things to notice. First, the leading less-than is optional. If omitted, Perl assumes that you want to open the file for reading.
The other important thing to notice is that, just as in the shell, any white space before or after the filename is ignored. This is good, because you wouldn't want these to do different things:
open INFO, "<datafile"
open INFO, "< datafile"
open INFO, "< datafile"
Ignoring surround whitespace also helps for when you read a filename in from a different file, and forget to trim it before opening:
$filename = <INFO>; # oops, \n still there
open(EXTRA, "< $filename") || die "can't open $filename: $!";
This is not a bug, but a feature. Because
open mimics the shell in its style of using redirection arrows to specify how to open the file, it also does so with respect to extra white space around the filename itself as well. For accessing files with naughty names, see
Dispelling the Dweomer.
Pipe Opens
In C, when you want to open a file using the standard I/O library, you use the
fopen function, but when opening a pipe, you use the
popen function. But in the shell, you just use a different redirection character. That's also the case for Perl. The
open call remains the same--just its argument differs.
If the leading character is a pipe symbol,
open starts up a new command and open a write-only filehandle leading into that command. This lets you write into that handle and have what you write show up on that command's standard input. For example:
open(PRINTER, "| lpr -Plp1") || die "can't run lpr: $!";
print PRINTER "stuff\n";
close(PRINTER) || die "can't close lpr: $!";
If the trailing character is a pipe, you start up a new command and open a read-only filehandle leading out of that command. This lets whatever that command writes to its standard output show up on your handle for reading. For example:
open(NET, "netstat -i -n |") || die "can't fun netstat: $!";
while (<NET>) { } # do something with input
close(NET) || die "can't close netstat: $!";
What happens if you try to open a pipe to or from a non-existent command? If possible, Perl will detect the failure and set
$! as usual. But if the command contains special shell characters, such as
> or
* , called 'metacharacters', Perl does not execute the command directly. Instead, Perl runs the shell, which then tries to run the command. This means that it's the shell that gets the error indication. In such a case, the
open call will only indicate failure if Perl can't even run the shell. See L<perlfaq8/"How can I capture STDERR from an external command?"> to see how to cope with this. There's also an explanation in
perlipc.
If you would like to open a bidirectional pipe, the IPC::Open2 library will handle this for you. Check out
perlipc, Bidirectional Communication with Another Process
The Minus File
Again following the lead of the standard shell utilities, Perl's
open function treats a file whose name is a single minus, "-", in a special way. If you open minus for reading, it really means to access the standard input. If you open minus for writing, it really means to access the standard output.
If minus can be used as the default input or default output, what happens if you open a pipe into or out of minus? What's the default command it would run? The same script as you're currently running! This is actually a stealth
fork hidden inside an
open call. See
perlipc, Safe Pipe Opens for details.
Mixing Reads and Writes
It is possible to specify both read and write access. All you do is add a "+" symbol in front of the redirection. But as in the shell, using a less-than on a file never creates a new file; it only opens an existing one. On the other hand, using a greater-than always clobbers (truncates to zero length) an existing file, or creates a brand-new one if there isn't an old one. Adding a "+" for read-write doesn't affect whether it only works on existing files or always clobbers existing ones.
open(WTMP, "+< /usr/adm/wtmp")
|| die "can't open /usr/adm/wtmp: $!";
open(SCREEN, "+> /tmp/lkscreen")
|| die "can't open /tmp/lkscreen: $!";
open(LOGFILE, "+>> /tmp/applog"
|| die "can't open /tmp/applog: $!";
The first one won't create a new file, and the second one will always clobber an old one. The third one will create a new file if necessary and not clobber an old one, and it will allow you to read at any point in the file, but all writes will always go to the end. In short, the first case is substantially more common than the second and third cases, which are almost always wrong. (If you know C, the plus in Perl's
open is historically derived from the one in C's fopen(3S), which it ultimately calls.)
In fact, when it comes to updating a file, unless you're working on a binary file as in the WTMP case above, you probably don't want to use this approach for updating. Instead, Perl's
-i flag comes to the rescue. The following command takes all the C, C++, or yacc source or header files and changes all their foo's to bar's, leaving the old version in the original file name with a ".orig" tacked on the end:
$ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy]
This is a short cut for some renaming games that are really the best way to update textfiles. See the second question in
perlfaq5 for more details.
Filters
One of the most common uses for
open is one you never even notice. When you process the ARGV filehandle using
<ARGV> , Perl actually does an implicit open on each file in @ARGV. Thus a program called like this:
$ myprogram file1 file2 file3
Can have all its files opened and processed one at a time using a construct no more complex than:
while (<>) {
# do something with $_
}
If @ARGV is empty when the loop first begins, Perl pretends you've opened up minus, that is, the standard input. In fact, $ARGV, the currently open file during
<ARGV> processing, is even set to "-" in these circumstances.
You are welcome to pre-process your @ARGV before starting the loop to make sure it's to your liking. One reason to do this might be to remove command options beginning with a minus. While you can always roll the simple ones by hand, the Getopts modules are good for this.
use Getopt::Std;
# -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_o
getopts("vDo:");
# -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o}
getopts("vDo:", \%args);
Or the standard Getopt::Long module to permit named arguments:
use Getopt::Long;
GetOptions( "verbose" => \$verbose, # --verbose
"Debug" => \$debug, # --Debug
"output=s" => \$output );
# --output=somestring or --output somestring
Another reason for preprocessing arguments is to make an empty argument list default to all files:
@ARGV = glob("*") unless @ARGV;
You could even filter out all but plain, text files. This is a bit silent, of course, and you might prefer to mention them on the way.
@ARGV = grep { -f && -T } @ARGV;
If you're using the
-n or
-p command-line options, you should put changes to @ARGV in a
BEGIN{} block.
Remember that a normal
open has special properties, in that it might call fopen(3S) or it might called popen(3S), depending on what its argument looks like; that's why it's sometimes called "magic open". Here's an example:
$pwdinfo = `domainname` =~ /^(\(none\))?$/
? '< /etc/passwd'
: 'ypcat passwd |';
open(PWD, $pwdinfo)
or die "can't open $pwdinfo: $!";
This sort of thing also comes into play in filter processing. Because
<ARGV> processing employs the normal, shell-style Perl
open , it respects all the special things we've already seen:
$ myprogram f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
That program will read from the file
f1 , the process
cmd1 , standard input (
tmpfile in this case), the
f2 file, the
cmd2 command, and finally the
f3 file.
Yes, this also means that if you have a file named "-" (and so on) in your directory, that they won't be processed as literal files by
open . You'll need to pass them as "./-" much as you would for the
rm program. Or you could use
sysopen as described below.
One of the more interesting applications is to change files of a certain name into pipes. For example, to autoprocess gzipped or compressed files by decompressing them with
gzip :
@ARGV = map { /^\.(gz|Z)$/ ? "gzip -dc $_ |" : $_ } @ARGV;
Or, if you have the
GET program installed from LWP, you can fetch URLs before processing them:
@ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV;
It's not for nothing that this is called magic
<ARGV> . Pretty nifty, eh?
Open à la C
If you want the convenience of the shell, then Perl's
open is definitely the way to go. On the other hand, if you want finer precision than C's simplistic fopen(3S) provides, then you should look to Perl's
sysopen , which is a direct hook into the open(2) system call. That does mean it's a bit more involved, but that's the price of precision.
sysopen takes 3 (or 4) arguments.
sysopen HANDLE, PATH, FLAGS, [MASK]
The HANDLE argument is a filehandle just as with
open . The PATH is a literal path, one that doesn't pay attention to any greater-thans or less-thans or pipes or minuses, nor ignore white space. If it's there, it's part of the path. The FLAGS argument contains one or more values derived from the Fcntl module that have been or'd together using the bitwise "|" operator. The final argument, the MASK, is optional; if present, it is combined with the user's current umask for the creation mode of the file. You should usually omit this.
Although the traditional values of read-only, write-only, and read-write are 0, 1, and 2 respectively, this is known not to hold true on some systems. Instead, it's best to load in the appropriate constants first from the Fcntl module, which supplies the following standard flags:
O_RDONLY Read only
O_WRONLY Write only
O_RDWR Read and write
O_CREAT Create the file if it doesn't exist
O_EXCL Fail if the file already exists
O_APPEND Append to the file
O_TRUNC Truncate the file
O_NONBLOCK Non-blocking access
Less common flags that are sometimes available on some operating systems include
O_BINARY ,
O_TEXT ,
O_SHLOCK ,
O_EXLOCK ,
O_DEFER ,
O_SYNC ,
O_ASYNC ,
O_DSYNC ,
O_RSYNC ,
O_NOCTTY ,
O_NDELAY and
O_LARGEFILE . Consult your open(2) manpage or its local equivalent for details. (Note: starting from Perl release 5.6 the O_LARGEFILE flag, if available, is automatically added to the sysopen() flags because large files are the default.)
Here's how to use
sysopen to emulate the simple
open calls we had before. We'll omit the
|| die $! checks for clarity, but make sure you always check the return values in real code. These aren't quite the same, since
open will trim leading and trailing white space, but you'll get the idea:
To open a file for reading:
open(FH, "< $path");
sysopen(FH, $path, O_RDONLY);
To open a file for writing, creating a new file if needed or else truncating an old file:
open(FH, "> $path");
sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT);
To open a file for appending, creating one if necessary:
open(FH, ">> $path");
sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT);
To open a file for update, where the file must already exist:
open(FH, "+< $path");
sysopen(FH, $path, O_RDWR);
And here are things you can do with
sysopen that you cannot do with a regular
open . As you see, it's just a matter of controlling the flags in the third argument.
To open a file for writing, creating a new file which must not previously exist:
sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);
To open a file for appending, where that file must already exist:
sysopen(FH, $path, O_WRONLY | O_APPEND);
To open a file for update, creating a new file if necessary:
sysopen(FH, $path, O_RDWR | O_CREAT);
To open a file for update, where that file must not already exist:
sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT);
To open a file without blocking, creating one if necessary:
sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT);
Permissions à la mode
If you omit the MASK argument to
sysopen , Perl uses the octal value 0666. The normal MASK to use for executables and directories should be 0777, and for anything else, 0666.
Why so permissive? Well, it isn't really. The MASK will be modified by your process's current
umask . A umask is a number representing
disabled permissions bits; that is, bits that will not be turned on in the created files' permissions field.
For example, if your
umask were 027, then the 020 part would disable the group from writing, and the 007 part would disable others from reading, writing, or executing. Under these conditions, passing
sysopen 0666 would create a file with mode 0640, since
0666 &~ 027 is 0640.
You should seldom use the MASK argument to
sysopen() . That takes away the user's freedom to choose what permission new files will have. Denying choice is almost always a bad thing. One exception would be for cases where sensitive or private data is being stored, such as with mail folders, cookie files, and internal temporary files.
Obscure Open Tricks
Re-Opening Files (dups)
Sometimes you already have a filehandle open, and want to make another handle that's a duplicate of the first one. In the shell, we place an ampersand in front of a file descriptor number when doing redirections. For example,
2>&1 makes descriptor 2 (that's STDERR in Perl) be redirected into descriptor 1 (which is usually Perl's STDOUT). The same is essentially true in Perl: a filename that begins with an ampersand is treated instead as a file descriptor if a number, or as a filehandle if a string.
open(SAVEOUT, ">&SAVEERR") || die "couldn't dup SAVEERR: $!";
open(MHCONTEXT, "<&4") || die "couldn't dup fd4: $!";
That means that if a function is expecting a filename, but you don't want to give it a filename because you already have the file open, you can just pass the filehandle with a leading ampersand. It's best to use a fully qualified handle though, just in case the function happens to be in a different package:
somefunction("&main::LOGFILE");
This way if somefunction() is planning on opening its argument, it can just use the already opened handle. This differs from passing a handle, because with a handle, you don't open the file. Here you have something you can pass to open.
If you have one of those tricky, newfangled I/O objects that the C++ folks are raving about, then this doesn't work because those aren't a proper filehandle in the native Perl sense. You'll have to use fileno() to pull out the proper descriptor number, assuming you can:
use IO::Socket;
$handle = IO::Socket::INET->new("www.perl.com:80");
$fd = $handle->fileno;
somefunction("&$fd"); # not an indirect function call
It can be easier (and certainly will be faster) just to use real filehandles though:
use IO::Socket;
local *REMOTE = IO::Socket::INET->new("www.perl.com:80");
die "can't connect" unless defined(fileno(REMOTE));
somefunction("&main::REMOTE");
If the filehandle or descriptor number is preceded not just with a simple "&" but rather with a "&=" combination, then Perl will not create a completely new descriptor opened to the same place using the dup(2) system call. Instead, it will just make something of an alias to the existing one using the fdopen(3S) library call This is slightly more parsimonious of systems resources, although this is less a concern these days. Here's an example of that:
$fd = $ENV{"MHCONTEXTFD"};
open(MHCONTEXT, "<&=$fd") or die "couldn't fdopen $fd: $!";
If you're using magic
<ARGV> , you could even pass in as a command line argument in @ARGV something like
"<&=$MHCONTEXTFD" , but we've never seen anyone actually do this.
Dispelling the Dweomer
Perl is more of a DWIMmer language than something like Java--where DWIM is an acronym for "do what I mean". But this principle sometimes leads to more hidden magic than one knows what to do with. In this way, Perl is also filled with
dweomer , an obscure word meaning an enchantment. Sometimes, Perl's DWIMmer is just too much like dweomer for comfort.
If magic
open is a bit too magical for you, you don't have to turn to
sysopen . To open a file with arbitrary weird characters in it, it's necessary to protect any leading and trailing whitespace. Leading whitespace is protected by inserting a
"./" in front of a filename that starts with whitespace. Trailing whitespace is protected by appending an ASCII NUL byte (
"\0" ) at the end off the string.
$file =~ s#^(\s)#./$1#;
open(FH, "< $file\0") || die "can't open $file: $!";
This assumes, of course, that your system considers dot the current working directory, slash the directory separator, and disallows ASCII NULs within a valid filename. Most systems follow these conventions, including all POSIX systems as well as proprietary Microsoft systems. The only vaguely popular system that doesn't work this way is the proprietary Macintosh system, which uses a colon where the rest of us use a slash. Maybe
sysopen isn't such a bad idea after all.
If you want to use
<ARGV> processing in a totally boring and non-magical way, you could do this first:
# "Sam sat on the ground and put his head in his hands.
# 'I wish I had never come here, and I don't want to see
# no more magic,' he said, and fell silent."
for (@ARGV) {
s#^([^./])#./$1#;
$_ .= "\0";
}
while (<>) {
# now process $_
}
But be warned that users will not appreciate being unable to use "-" to mean standard input, per the standard convention.
Paths as Opens
You've probably noticed how Perl's
warn and
die functions can produce messages like:
Some warning at scriptname line 29, <FH> line 7.
That's because you opened a filehandle FH, and had read in seven records from it. But what was the name of the file, not the handle?
If you aren't running with
strict refs , or if you've turn them off temporarily, then all you have to do is this:
open($path, "< $path") || die "can't open $path: $!";
while (<$path>) {
# whatever
}
Since you're using the pathname of the file as its handle, you'll get warnings more like
Some warning at scriptname line 29, </etc/motd> line 7.
Single Argument Open
Remember how we said that Perl's open took two arguments? That was a passive prevarication. You see, it can also take just one argument. If and only if the variable is a global variable, not a lexical, you can pass
open just one argument, the filehandle, and it will get the path from the global scalar variable of the same name.
$FILE = "/etc/motd";
open FILE or die "can't open $FILE: $!";
while (<FILE>) {
# whatever
}
Why is this here? Someone has to cater to the hysterical porpoises. It's something that's been in Perl since the very beginning, if not before.
Playing with STDIN and STDOUT
One clever move with STDOUT is to explicitly close it when you're done with the program.
END { close(STDOUT) || die "can't close stdout: $!" }
If you don't do this, and your program fills up the disk partition due to a command line redirection, it won't report the error exit with a failure status.
You don't have to accept the STDIN and STDOUT you were given. You are welcome to reopen them if you'd like.
open(STDIN, "< datafile")
|| die "can't open datafile: $!";
open(STDOUT, "> output")
|| die "can't open output: $!";
And then these can be read directly or passed on to subprocesses. This makes it look as though the program were initially invoked with those redirections from the command line.
It's probably more interesting to connect these to pipes. For example:
$pager = $ENV{PAGER} || "(less || more)";
open(STDOUT, "| $pager")
|| die "can't fork a pager: $!";
This makes it appear as though your program were called with its stdout already piped into your pager. You can also use this kind of thing in conjunction with an implicit fork to yourself. You might do this if you would rather handle the post processing in your own program, just in a different process:
head(100);
while (<>) {
print;
}
sub head {
my $lines = shift || 20;
return unless $pid = open(STDOUT, "|-");
die "cannot fork: $!" unless defined $pid;
while (<STDIN>) {
print;
last if --$lines < 0;
}
exit;
}
This technique can be applied to repeatedly push as many filters on your output stream as you wish.
Other I/O Issues
These topics aren't really arguments related to
open or
sysopen , but they do affect what you do with your open files.
Opening Non-File Files
When is a file not a file? Well, you could say when it exists but isn't a plain file. We'll check whether it's a symbolic link first, just in case.
if (-l $file || ! -f _) {
print "$file is not a plain file\n";
}
What other kinds of files are there than, well, files? Directories, symbolic links, named pipes, Unix-domain sockets, and block and character devices. Those are all files, too--just not
plain files. This isn't the same issue as being a text file. Not all text files are plain files. Not all plain files are textfiles. That's why there are separate
-f and
-T file tests.
To open a directory, you should use the
opendir function, then process it with
readdir , carefully restoring the directory name if necessary:
opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
while (defined($file = readdir(DIR))) {
# do something with "$dirname/$file"
}
closedir(DIR);
If you want to process directories recursively, it's better to use the File::Find module. For example, this prints out all files recursively, add adds a slash to their names if the file is a directory.
@ARGV = qw(.) unless @ARGV;
use File::Find;
find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;
This finds all bogus symbolic links beneath a particular directory:
find sub { print "$File::Find::name\n" if -l && !-e }, $dir;
As you see, with symbolic links, you can just pretend that it is what it points to. Or, if you want to know
what it points to, then
readlink is called for:
if (-l $file) {
if (defined($whither = readlink($file))) {
print "$file points to $whither\n";
} else {
print "$file points nowhere: $!\n";
}
}
Named pipes are a different matter. You pretend they're regular files, but their opens will normally block until there is both a reader and a writer. You can read more about them in
perlipc, Named Pipes. Unix-domain sockets are rather different beasts as well; they're described in
perlipc, Unix-Domain TCP Clients and Servers.
When it comes to opening devices, it can be easy and it can tricky. We'll assume that if you're opening up a block device, you know what you're doing. The character devices are more interesting. These are typically used for modems, mice, and some kinds of printers. This is described in L<perlfaq8/"How do I read and write the serial port?"> It's often enough to open them carefully:
sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)
# (O_NOCTTY no longer needed on POSIX systems)
or die "can't open /dev/ttyS1: $!";
open(TTYOUT, "+>&TTYIN")
or die "can't dup TTYIN: $!";
$ofh = select(TTYOUT); $| = 1; select($ofh);
print TTYOUT "+++at\015";
$answer = <TTYIN>;
With descriptors that you haven't opened using
sysopen , such as a socket, you can set them to be non-blocking using
fcntl :
use Fcntl;
fcntl(Connection, F_SETFL, O_NONBLOCK)
or die "can't set non blocking: $!";
Rather than losing yourself in a morass of twisting, turning
ioctl s, all dissimilar, if you're going to manipulate ttys, it's best to make calls out to the stty(1) program if you have it, or else use the portable POSIX interface. To figure this all out, you'll need to read the termios(3) manpage, which describes the POSIX interface to tty devices, and then
POSIX, which describes Perl's interface to POSIX. There are also some high-level modules on CPAN that can help you with these games. Check out Term::ReadKey and Term::ReadLine.
What else can you open? To open a connection using sockets, you won't use one of Perl's two open functions. See
perlipc, Sockets: Client/Server Communication for that. Here's an example. Once you have it, you can use FH as a bidirectional filehandle.
use IO::Socket;
local *FH = IO::Socket::INET->new("www.perl.com:80");
For opening up a URL, the LWP modules from CPAN are just what the doctor ordered. There's no filehandle interface, but it's still easy to get the contents of a document:
use LWP::Simple;
$doc = get('http://www.linpro.no/lwp/');
Binary Files
On certain legacy systems with what could charitably be called terminally convoluted (some would say broken) I/O models, a file isn't a file--at least, not with respect to the C standard I/O library. On these old systems whose libraries (but not kernels) distinguish between text and binary streams, to get files to behave properly you'll have to bend over backwards to avoid nasty problems. On such infelicitous systems, sockets and pipes are already opened in binary mode, and there is currently no way to turn that off. With files, you have more options.
Another option is to use the
binmode function on the appropriate handles before doing regular I/O on them:
binmode(STDIN);
binmode(STDOUT);
while (<STDIN>) { print }
Passing
sysopen a non-standard flag option will also open the file in binary mode on those systems that support it. This is the equivalent of opening the file normally, then calling
binmode ing on the handle.
sysopen(BINDAT, "records.data", O_RDWR | O_BINARY)
|| die "can't open records.data: $!";
Now you can use
read and
print on that handle without worrying about the system non-standard I/O library breaking your data. It's not a pretty picture, but then, legacy systems seldom are. CP/M will be with us until the end of days, and after.
On systems with exotic I/O systems, it turns out that, astonishingly enough, even unbuffered I/O using
sysread and
syswrite might do sneaky data mutilation behind your back.
while (sysread(WHENCE, $buf, 1024)) {
syswrite(WHITHER, $buf, length($buf));
}
Depending on the vicissitudes of your runtime system, even these calls may need
binmode or
O_BINARY first. Systems known to be free of such difficulties include Unix, the Mac OS, Plan 9, and Inferno.
File Locking
In a multitasking environment, you may need to be careful not to collide with other processes who want to do I/O on the same files as others are working on. You'll often need shared or exclusive locks on files for reading and writing respectively. You might just pretend that only exclusive locks exist.
Never use the existence of a file
-e $file as a locking indication, because there is a race condition between the test for the existence of the file and its creation. Atomicity is critical.
Perl's most portable locking interface is via the
flock function, whose simplicity is emulated on systems that don't directly support it, such as SysV or WindowsNT. The underlying semantics may affect how it all works, so you should learn how
flock is implemented on your system's port of Perl.
File locking
does not lock out another process that would like to do I/O. A file lock only locks out others trying to get a lock, not processes trying to do I/O. Because locks are advisory, if one process uses locking and another doesn't, all bets are off.
By default, the
flock call will block until a lock is granted. A request for a shared lock will be granted as soon as there is no exclusive locker. A request for an exclusive lock will be granted as soon as there is no locker of any kind. Locks are on file descriptors, not file names. You can't lock a file until you open it, and you can't hold on to a lock once the file has been closed.
Here's how to get a blocking shared lock on a file, typically used for reading:
use 5.004;
use Fcntl qw(:DEFAULT :flock);
open(FH, "< filename") or die "can't open filename: $!";
flock(FH, LOCK_SH) or die "can't lock filename: $!";
# now read from FH
You can get a non-blocking lock by using
LOCK_NB .
flock(FH, LOCK_SH | LOCK_NB)
or die "can't lock filename: $!";
This can be useful for producing more user-friendly behaviour by warning if you're going to be blocking:
use 5.004;
use Fcntl qw(:DEFAULT :flock);
open(FH, "< filename") or die "can't open filename: $!";
unless (flock(FH, LOCK_SH | LOCK_NB)) {
$| = 1;
print "Waiting for lock...";
flock(FH, LOCK_SH) or die "can't lock filename: $!";
print "got it.\n"
}
# now read from FH
To get an exclusive lock, typically used for writing, you have to be careful. We
sysopen the file so it can be locked before it gets emptied. You can get a nonblocking version using
LOCK_EX | LOCK_NB .
use 5.004;
use Fcntl qw(:DEFAULT :flock);
sysopen(FH, "filename", O_WRONLY | O_CREAT)
or die "can't open filename: $!";
flock(FH, LOCK_EX)
or die "can't lock filename: $!";
truncate(FH, 0)
or die "can't truncate filename: $!";
# now write to FH
Finally, due to the uncounted millions who cannot be dissuaded from wasting cycles on useless vanity devices called hit counters, here's how to increment a number in a file safely:
use Fcntl qw(:DEFAULT :flock);
sysopen(FH, "numfile", O_RDWR | O_CREAT)
or die "can't open numfile: $!";
# autoflush FH
$ofh = select(FH); $| = 1; select ($ofh);
flock(FH, LOCK_EX)
or die "can't write-lock numfile: $!";
$num = <FH> || 0;
seek(FH, 0, 0)
or die "can't rewind numfile : $!";
print FH $num+1, "\n"
or die "can't write numfile: $!";
truncate(FH, tell(FH))
or die "can't truncate numfile: $!";
close(FH)
or die "can't close numfile: $!";
IO Layers
In Perl 5.8.0 a new I/O framework called "PerlIO" was introduced. This is a new "plumbing" for all the I/O happening in Perl; for the most part everything will work just as it did, but PerlIO brought in also some new features, like the capability of think of I/O as "layers". One I/O layer may in addition to just moving the data also do transformations on the data. Such transformations may include compression and decompression, encryption and decryption, and transforming between various character encodings.
Full discussion about the features of PerlIO is out of scope for this tutorial, but here is how to recognize the layers being used:
The three-(or more)-argument form of open() is being used and the second argument contains something else in addition to the usual '<' , '>' , '>>' , '|' and their variants, for example:
open(my $fh, "<:utf8", $fn);
The two-argument form of binmode<open() is being used, for example
binmode($fh, ":encoding(utf16)");
For more detailed discussion about PerlIO see
perlio?; for more detailed discussion about Unicode and I/O see
perluniintro.
SEE ALSO
The
open and
sysopen function in perlfunc(1); the standard open(2), dup(2), fopen(3), and fdopen(3) manpages; the POSIX documentation.
AUTHOR and COPYRIGHT
Copyright 1998 Tom Christiansen.
This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.
Irrespective of its distribution, all code examples in these files are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.
HISTORY
First release: Sat Jan 9 08:09:11 MST 1999
Kommentare:
--
HaraldBongartz - 30 Aug 2008