7. File Access


    s -> s.m!("bleu", s.println)

Sys::stdall.lines(s ->
    #s.m!("\d", warn("No digit found.\n"))
    warn("No digit found.\n") if not s.m?("\d")
    print("Read: {s}")

Opening a File

fd = open(filename, W)


Opening Files with Unusual Filenames

# ;pp

Expanding Tildes in Filenames

"~".expand_path                         # a la ruby

Making Perl Report Filenames in Errors

# default is exception on error => good error messages
# with open(f, Safe), no exception on file access

Creating Temporary Files

f = tmpfile("foo") or tmpfile("/tmp/fooXXXXXX") # "foo" gives file $TMPDIR/fooXXXXXX
f.output("bar")                 # output "bar" to a temporary file named f

Storing Files Inside Your Program Text

# use a string:
DATA = q(
# your data goes here

Writing a Filter

Modifying a File in Place with Temporary File

Modifying a File in Place with -i Switch

Modifying a File in Place Without a Temporary File

l = file.open.lines.map(subst(, "DATE", localtime()))

Locking a File

f = "numfile".open(R | W | Lock)
# Now we have acquired the lock, it's safe for I/O
num = f.whole.m("(\d+)") or 0
f.truncate!(0)            # truncate! ensure the current seek is <= current size

Flushing Output


Reading from Many Filehandles Without Blocking

l = [ fh1, fh2, fh3 ].select
if fh1.mem?(l) then
    # do something with fh1
if fh2.mem?(l) then
    # do something with fh2

Doing Non-Blocking I/O

modem = "/dev/cua0".open(Non_block | W)

Determining the Number of Bytes to Read

# don't do it, use "whole" with Non_block

Storing Filehandles in Variables

# ;pp

Caching Open Output Filehandles

Printing to Many Filehandles Simultaneously

# maybe introduce Out_files !< Out_file

Opening and Closing File Descriptors by Number

fh = fdopen(fdnum, R) # open file descriptor 3 for reading

Copying Filehandles

alias = original
outcopy = Sys::stdout.clone
incopy = Sys::stdin.clone

Program: netlock

Program: lockarea