|
14 Files/folders
<
open
for
reading
-
default
>
open
for
writing
>>
open
for
appending
+<
open
for
both reading
and
writing
+>
open
for
both reading
and
writing
| (before file name) treat file as command into which Perl is to
pipe
text
| (after file name) treat file as command from which input is to be piped to Perl
<>
# special operator for reading from files
# returns 1 line if used in scalar context
# returns all lines is used in array context
---
open
for
reading:
open
(filehandle, pathname)
# make up your own name for filehandle
open
(Handle,
"file.txt"
)
# returns nonzero value if open is successful
open
(Handle,
"file.txt"
)
||
die
# right side is not executed if open is successful
open
(Handle,
'c:
\t
emp
\f
ile.txt'
)
# note single quotes that allows use of backslash
# if Handle is re-used, old file is closed
close
(Handle)
$filedata
=
<
fHandle
>
# read one line from the file into the scalar $filedata
@filedata
=
<
fHandle
>
# read all lines from the file into the array @filedata
<>
angle operator used
for
reading
/
writing files
$c
=<
STDIN
>
;
# reads from a keyboard (also gets the newline character)
chomp
$c
;
# removes the newline character
while
(
defined
(
$a
=<
MYFILE
>
))
{
print
$a
;
}
while
(
<
MYFILE
>
)
# while puts input line int0 special variable $_ until EOF
{
print
$_
;
}
---
open
for
writing:
open
(filehandle,
">pathname"
)
# open to overwrite
open
(filehandle,
">>pathname"
)
# open to append
---
write
to file:
print
MYFILE LIST
# no comma (except in list)
---
File Test Operators:
$a
=
(
-
e
'file.txt'
)
# True if file exists
$a
=
(
-
s
'file.txt'
)
# returns size of file in bytes
$a
=
(
-
d
'c:
\t
emp'
)
# True if 'c:\temp' is a directory
---
rename
a file:
rename
(
$old
,
$new
);
---
to
delete
line at end of a file,
use
'tell'
and
'truncate'
statements
---
read
a single character from a file:
use
the
'getc'
function
|