ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
17.5 Variable-Length ( Text) DatabasesMany UNIX system databases (and quite a few user-created databases) are a series of human-readable text lines, with one record per line. For example, the password file consists of one line per user on the system, and the hosts file contains one line per hostname. Most often, these databases are updated with simple text editors. Updating such a database consists of reading it all into a temporary area (either memory or another disk file), making the necessary changes, and then either writing the result back to the original file or creating a new file with the same name after deleting or renaming the old version. You can think of this as a copy pass: the data is copied from the original database to a new version of the database, making changes during the copy. Perl supports a copy-pass-style edit on line-oriented databases using inplace editing. Inplace editing is a modification of the way the diamond operator ( To trigger the inplace editing mode, set a value into the When the $ARGV = shift @ARGV; open(ARGV,"<$ARGV"); rename($ARGV,"$ARGV$^I"); ## INPLACE ## unlink($ARGV); ## INPLACE ## open(ARGVOUT,">$ARGV"); ## INPLACE ## select(ARGVOUT); ## INPLACE ## The effect is that reads from the diamond operator come from the old file, and writes to the default filehandle go to a new copy of the file. The old file remains in a backup file, which is the filename with a suffix equal to the value of the Typical values for Here's a way to change everyone's login shell to /bin/sh by editing the password file: @ARGV = ("/etc/passwd"); # prime the diamond operator $^I = ".bak"; # write /etc/passwd.bak for safety while (<>) { # main loop, once for each line of /etc/passwd s#:[^:]*$#:/bin/sh#; # change the shell to /bin/sh print; # send output to ARGVOUT: the new /etc/passwd } As you can see, this program is pretty simple. In fact, the same program can be generated entirely with a few command-line arguments, as in: perl -p -i.bak -e 's#:[^:]*$#:/bin/sh#' /etc/passwd The Command-line arguments are discussed in greater detail in Programming Perl and the perlrun manpage. |