Tải bản đầy đủ - 0 (trang)
Chapter 10. Getting a Handle on Files

Chapter 10. Getting a Handle on Files

Tải bản đầy đủ - 0trang

WhenopeningtextfilesonWin32platforms,the\r\n

(charactersforreturnandnewline)aretranslatedinto\nwhen

textfilesarereadfromdisk,andthe^Zcharacterisreadasan

end-of-filemarker(EOF).Thefollowingfunctionsforopening

filesshouldworkfinewithtextfilesbutwillcauseaproblem

withbinaryfiles.(See"Win32BinaryFiles"onpage292.)



10.1.2.OpenforReading

Thefollowingexamplesillustratehowtoopenfilesforreading.

EventhoughtheexamplesrepresentUNIXfiles,theywillwork

thesamewayonWindows,MacOS,etc.



Format

1open(FILEHANDLE,"FILENAME");

2open(FILEHANDLE,"
2open(FILEHANDLE);

3openFILEHANDLE;

Example10.1.

1open(MYHANDLE,"myfile");

2open(FH,"
3open(MYHANDLE);



Explanation

1. Theopenfunctionwillcreatethefilehandle

MYHANDLEandattachittothesystemfilemyfile.

Thefilewillbeopenedforreading.Sinceafull

pathnameisnotspecifiedformyfile,itmustbein

thecurrentworkingdirectory,andyoumusthave

readpermissiontoopenitforreading.

2. TheopenfunctionwillcreatethefilehandleFHand

attachittothesystemfile/etc/passwd.Thefilewill

beopenedforreading,butthistimethe
isusedtoindicatetheoperation.The
notnecessarybutmayhelpclarifythatthisisa

readoperation.Thefullpathnameisspecifiedfor

passwd.

3. IfFILENAMEisomitted,thenameofthefilehandle

isthesamenameasascalarvariablepreviously

defined.Thescalarvariablehasbeenassignedthe

nameoftherealfile.Intheexample,thefilename

couldhavebeendefinedas

$MYHANDLE="myfile";

open(MYHANDLE);

Theopenfunctionwillcreatethefilehandle

MYHANDLEandattachittothevalueofthe

variable,$MYHANDLE.Theeffectwillbethesame

asthefirstexample.Theparenthesesareoptional.



ClosingtheFilehandle

Theclosefunctionclosesthefile,pipe,socket,ordevice



attachedtoFILEHANDLE.OnceFILEHANDLEisopened,itstays

openuntilthescriptendsoryoucalltheopenfunctionagain.

(ThenextcalltoopenclosesFILEHANDLEbeforereopeningit.)

Ifyoudon'texplicitlyclosethefile,whenyoureopenitthisway,

thelinecountervariable,$.,willnotbereset.Closingapipe

causestheprocesstowaituntilthepipeiscompleteand

reportsthestatusinthe$!variable(see"ThedieFunction"on

page287).It'sagoodideatoexplicitlyclosefilesandhandles

afteryouarefinishedusingthem.



Format

close(FILEHANDLE);

closeFILEHANDLE;



Example10.2.

1open(INFILE,"datebook");

close(INFILE);



Explanation

1. Theuser-definedfilehandleINFILEwillbeclosed.



ThedieFunction

Inthefollowingexamples,thediefunctionisusedifacallto

theopenfunctionfails.IfPerlcannotopenthefile,thedie

functionisusedtoexitthePerlscriptandprintamessageto

STDERR,usuallythescreen.

IfyouweretogotoyourshellorMS-DOSpromptandtype

catjunk(UNIX)



or

typejunk(DOS)



andifjunkisanonexistentfile,thefollowingsystemerror

wouldappearonyourscreen:



cat:junk:Nosuchfileordirectory(UNIX"cat"command)

Thesystemcannotfindthefilespecified.(Windows"type"co



Whenusingthediefunction,Perlprovidesaspecialvariable$!

toholdthevalueofthesystemerror(see"ErrorHandling"on

page755)thatoccurswhenyouareunabletosuccessfullyopen

afileorexecuteasystemutility.Thisisveryusefulfor



detectingaproblemwiththefilehandlebeforecontinuingwith

theexecutionofthescript.(SeeuseofCarp.pmdiscussedin

Example12.10onpage384.)

Example10.3.

(LinefromScript)

1open(MYHANDLE,"/etc/password)||die"Can'topen:$!\n"

2open(MYHANDLE,"/etc/password)ordie"Can'topen:$!\n"

(Output)

1Can'topen:Nosuchfileordirectory

(LinefromScript)

3open(MYHANDLE,"/etc/password")||die"Can'topen:"

(Output)

3Can'topen:Nosuchfileordirectoryat./handleline3.



Explanation

1. Whentryingtoopenthefile/etc/password,theopenfails

(itshouldbe/etc/passwd).Theshort-circuitoperator

causesitsrightoperandtoexecuteiftheleftoperandfails.

Thedieoperatorisexecuted.ThestringCan'topen:is

printed,followedbythesystemerrorNosuchfileor

directory.The\nsuppressesanyfurtheroutputfromthe

diefunction.Allofdie'soutputissenttoSTDERRafterthe

programexits.

2. Forreadability,youmaywanttousetheoroperator

insteadof||.

3. Thisisexactlylikethefirstexample,exceptthatthe\nhas

beenremovedfromthestringCan'topen:.Omittingthe\n

causesthediefunctiontoappendastringtotheoutput,

indicatingthelinenumberinthescriptwherethesystem

erroroccurred.



ReadingfromtheFilehandle

InExample10.4,afilecalleddatebookisopenedforreading.

Eachlinereadisassigned,inturn,to$_,thedefaultscalarthat

holdswhatwasjustreaduntiltheendoffileisreached.

Example10.4.

(TheTextFile:datebook)

SteveBlenheim

BettyBoop

LoriGortz

SirLancelot

NormaCord

JonDeLoach

KarenEvich



--------------------------------------------------------------(TheScript)

#!/usr/bin/perl

#Openafilewithafilehandle

1open(FILE,"datebook")||die"Can'topendatebook:$!\n";

2while(){

3printif/SirLancelot/;

4}

5close(FILE);

(Output)

3SirLancelot



Explanation

1. TheopenfunctionwillcreateafilehandlecalledFILE

(openedforreading)andattachthesystemfiledatebook

toit.Ifopenfailsbecausethefiledatebookdoesnotexist,

thedieoperatorwillprinttothescreen,Can'topen

datebook:Nosuchfileordirectory.

2. TheexpressioninthewhileloopisthefilehandleFILE,

enclosedinanglebrackets.Theanglebracketsarethe

operatorsusedforreadinginput.(Theyarenotpartofthe

filehandlename.)Whentheloopstarts,thefirstlinefrom

thefilehandleFILEwillbestoredinthe$_scalarvariable.

(Remember,the$_variableholdseachlineofinputfrom

thefile.)Ifithasnotreachedendoffile,theloopwill

continuetotakealineofinputfromthefile,execute

statements3and4,andcontinueuntilendoffileis

reached.

3. Thedefaultinputvariable$_isimplicitlyusedtoholdthe

currentlineofinputreadfromthefilehandle.Iftheline

containstheregularexpressionSirLancelot,thatline

(storedin$_)isprintedtoSTDOUT.Foreachloop

iteration,thenextlinereadisstoredin$_andtested.

4. Theclosingcurlybracemarkstheendoftheloopbody.

Whenthislineisreached,controlwillgobacktothetopof

theloop(line2)andthenextlineofinputwillberead

fromfile;thisprocesswillcontinueuntilallthelineshave

beenread.

5. Afterloopingthroughthefile,thefileisclosedbyclosing

thefilehandle.

Example10.5.



(TheTextFile:datebook)

SteveBlenheim

BettyBoop

LoriGortz

SirLancelot

NormaCord

JonDeLoach

KarenEvich



--------------------------------------------------------------(TheScript)

#!/usr/bin/perl

#Openafilewithafilehandle

1open(FILE,"datebook")||die"Can'topendatebook:$!\n";

2while($line=){

3print"$line"if$line=~/^Lori/;

4}

5close(FILE);

(Output)

3LoriGortz



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 10. Getting a Handle on Files

Tải bản đầy đủ ngay(0 tr)

×