Parent Directory
|
Revision Log
Revision 1 - (view) (download)
| 1 : | root | 1 | This is unix.info, produced by makeinfo version 4.0 from unix.texinfo. |
| 2 : | |||
| 3 : | |||
| 4 : | File: unix.info, Node: Input in sh, Next: Loops in sh, Prev: Tests in sh, Up: Bourne shell | ||
| 5 : | |||
| 6 : | Input from the user in sh | ||
| 7 : | ========================= | ||
| 8 : | |||
| 9 : | In shell you can read the value of a variable using the `read' | ||
| 10 : | command, with syntax | ||
| 11 : | |||
| 12 : | read VARIABLE | ||
| 13 : | |||
| 14 : | This reads in a string from the keyboard and terminates on a newline | ||
| 15 : | character. Another way to do this is to use the `input' command to | ||
| 16 : | access a particular logical device. The keyboard device in the current | ||
| 17 : | terminal is `/dev/tty', so that one writes | ||
| 18 : | VARIABLE = `line < /dev/tty` | ||
| 19 : | |||
| 20 : | which fetches a single line from the user. | ||
| 21 : | |||
| 22 : | Here are some examples of these commands. First a program which | ||
| 23 : | asks yes or no... | ||
| 24 : | #!/bin/sh | ||
| 25 : | # | ||
| 26 : | # Yes or no | ||
| 27 : | # | ||
| 28 : | |||
| 29 : | echo "Please answer yes or no: " | ||
| 30 : | |||
| 31 : | answer=`line < /dev/tty` | ||
| 32 : | |||
| 33 : | case $answer in | ||
| 34 : | |||
| 35 : | y* | Y* | j* | J* ) echo YES!! ;; | ||
| 36 : | |||
| 37 : | n* | N* ) echo NO!! ;; | ||
| 38 : | |||
| 39 : | *) echo "Can't you answer a simple question?" | ||
| 40 : | |||
| 41 : | esac | ||
| 42 : | |||
| 43 : | echo The end | ||
| 44 : | |||
| 45 : | Notice the use of pattern matching and the `|' `OR' symbol. | ||
| 46 : | #!/bin/sh | ||
| 47 : | # | ||
| 48 : | # Kernel check | ||
| 49 : | # | ||
| 50 : | |||
| 51 : | if test ! -f /vmunix # Check that the kernel is there! | ||
| 52 : | then | ||
| 53 : | echo "This is not BSD unix...hmmm" | ||
| 54 : | if [ -f /hp-ux ] | ||
| 55 : | then | ||
| 56 : | echo "It's a Hewlett Packard machine!" | ||
| 57 : | fi | ||
| 58 : | elif [ -w /vmunix ] | ||
| 59 : | then | ||
| 60 : | echo "HEY!! The kernel is writable my me!"; | ||
| 61 : | else | ||
| 62 : | echo "The kernel is write protected." | ||
| 63 : | echo "The system is safe from me today." | ||
| 64 : | fi | ||
| 65 : | |||
| 66 : | |||
| 67 : | File: unix.info, Node: Loops in sh, Next: Procedures and traps, Prev: Input in sh, Up: Bourne shell | ||
| 68 : | |||
| 69 : | Loops in sh | ||
| 70 : | =========== | ||
| 71 : | |||
| 72 : | The loop structures in the Bourne shell have the following syntax. | ||
| 73 : | while UNIX-COMMAND | ||
| 74 : | do | ||
| 75 : | commands | ||
| 76 : | done | ||
| 77 : | |||
| 78 : | The first command will most likely be a test but, as before, it could | ||
| 79 : | in principle be any UNIX command. The `until' loop, reminiscent of | ||
| 80 : | BCPL, carries out a task until its argument evaluates to TRUE. | ||
| 81 : | until UNIX-COMMAND | ||
| 82 : | do | ||
| 83 : | commands | ||
| 84 : | done | ||
| 85 : | |||
| 86 : | Finally the `for' structure has already been used above. | ||
| 87 : | for VARIABLE in LIST | ||
| 88 : | do | ||
| 89 : | COMMANDS | ||
| 90 : | done | ||
| 91 : | |||
| 92 : | Often we want to be able to use an array of values as the list which | ||
| 93 : | `for' parses, but Bourne shell has no array variables. This problem is | ||
| 94 : | usually solved by making a long string separated by, for example, | ||
| 95 : | colons. For example, the `$PATH' variable has the form | ||
| 96 : | PATH = /usr/bin:/bin:/local/gnu/bin | ||
| 97 : | |||
| 98 : | Bourne shell allows us to split such a string on whatever character we | ||
| 99 : | wish. Normally the split is made on spaces, but the variable `IFS' can | ||
| 100 : | be defined with a replacement. To make a loop over all directories in | ||
| 101 : | the command path we would therefore write | ||
| 102 : | IFS=: | ||
| 103 : | |||
| 104 : | for name in $PATH; do | ||
| 105 : | |||
| 106 : | COMMANDS | ||
| 107 : | |||
| 108 : | done | ||
| 109 : | |||
| 110 : | The best way to gain experience with these commands is through some | ||
| 111 : | examples. | ||
| 112 : | #!/bin/sh | ||
| 113 : | # | ||
| 114 : | # Get text from user repeatedly | ||
| 115 : | # | ||
| 116 : | |||
| 117 : | echo "Type away..." | ||
| 118 : | |||
| 119 : | while read TEXT | ||
| 120 : | do | ||
| 121 : | |||
| 122 : | echo You typed $TEXT | ||
| 123 : | |||
| 124 : | if [ "$TEXT" = "quit" ]; then | ||
| 125 : | echo "(So I quit!)" | ||
| 126 : | exit 0 | ||
| 127 : | fi | ||
| 128 : | |||
| 129 : | done | ||
| 130 : | |||
| 131 : | echo "HELP!" | ||
| 132 : | |||
| 133 : | This very simple script is a typical use for a while-loop. It gets text | ||
| 134 : | repeatedly until the user type `quit'. Since read never returns `false' | ||
| 135 : | unless an error occurs or it detects an EOF (end of file) character | ||
| 136 : | <CTRL-D>, it will never exit without some help from an `if' test. If it | ||
| 137 : | does receive a <CTRL-D> signal, the script prints `HELP!'. | ||
| 138 : | |||
| 139 : | #!/bin/sh | ||
| 140 : | # | ||
| 141 : | # Watch in the background for a particular user | ||
| 142 : | # and give alarm if he/she logs in | ||
| 143 : | # | ||
| 144 : | # To be run in the background, using & | ||
| 145 : | # | ||
| 146 : | |||
| 147 : | if [ $# -ne 1 ]; then | ||
| 148 : | echo "Give the name of the user as an argument" > /dev/tty | ||
| 149 : | exit 1 | ||
| 150 : | fi | ||
| 151 : | |||
| 152 : | echo "Looking for $1" | ||
| 153 : | |||
| 154 : | until users | grep -s $1 | ||
| 155 : | do | ||
| 156 : | sleep 60 | ||
| 157 : | done | ||
| 158 : | |||
| 159 : | echo "!!! WAKE UP !!!" > /dev/tty | ||
| 160 : | echo "User $1 just logged in" > /dev/tty | ||
| 161 : | |||
| 162 : | This script uses `grep' in `silent mode' (-s option). i.e. grep never | ||
| 163 : | writes anything to the terminal. The only thing we are interested in is | ||
| 164 : | the return code the piped command produces. If `grep' detects a line | ||
| 165 : | containing the username we are interested in, then the result evaluates | ||
| 166 : | to TRUE and the sleep-loop exits. | ||
| 167 : | |||
| 168 : | Our final example is the kind of script which is useful for a system | ||
| 169 : | administrator. It transfers over the Network Information Service | ||
| 170 : | database files so that a slave server is up to date. All we have to do | ||
| 171 : | is make a list of the files and place it in a `for' loop. The names | ||
| 172 : | used below are the actual names of the NIS maps, well known to system | ||
| 173 : | administrators. | ||
| 174 : | #!/bin/sh | ||
| 175 : | # | ||
| 176 : | # Update the NIS database maps on a client server. This program | ||
| 177 : | # shouldn't have to be run, but sometimes things go wrong and we | ||
| 178 : | # have to force a download from the main sever. | ||
| 179 : | # | ||
| 180 : | PATH=/etc/yp:/usr/etc/yp:$PATH | ||
| 181 : | |||
| 182 : | MASTER=myNISserver | ||
| 183 : | |||
| 184 : | for map in auto.direct auto.master ethers.byaddr ethers.byname\ | ||
| 185 : | group.bygid group.byname hosts.byaddr hosts.byname\ | ||
| 186 : | mail.aliases netgroup.byhost netgroup.byuser netgroup\ | ||
| 187 : | netid.byname networks.byaddr networks.byname passwd.byname\ | ||
| 188 : | passwd.byuid priss.byname protocols.byname protocols.bynumber\ | ||
| 189 : | rpc.bynumber services.byname services usenetgroups.byname; | ||
| 190 : | do | ||
| 191 : | ypxfr $1 -h $MASTER $map | ||
| 192 : | done | ||
| 193 : | |||
| 194 : | |||
| 195 : | File: unix.info, Node: Procedures and traps, Next: setuid setgid scripts, Prev: Loops in sh, Up: Bourne shell | ||
| 196 : | |||
| 197 : | Procedures and traps | ||
| 198 : | ==================== | ||
| 199 : | |||
| 200 : | One of the worthy features of the Bourne shell is that it allows you | ||
| 201 : | to define _subroutines_ or _procedures_. Subroutines work just like | ||
| 202 : | subroutines in any other programming language. They are executed in | ||
| 203 : | same shell (not as a sub-process). | ||
| 204 : | |||
| 205 : | Here is an interesting program which demonstrates two useful things | ||
| 206 : | at the same time. First of all, it shows how to make a hierachical | ||
| 207 : | subroutine structure using the Bourne shell. Secondly, it shows how | ||
| 208 : | the `trap' directive can be used to trap signals, so that Bourne shell | ||
| 209 : | programs can exit safely when they are killed or when CTRL-C is typed. | ||
| 210 : | |||
| 211 : | #!/bin/sh | ||
| 212 : | # | ||
| 213 : | # How to make a signal handler in Bourne Shell | ||
| 214 : | # using subroutines | ||
| 215 : | # | ||
| 216 : | |||
| 217 : | ##################################################### | ||
| 218 : | # Level 2 | ||
| 219 : | ##################################################### | ||
| 220 : | |||
| 221 : | ReallyQuit() | ||
| 222 : | { | ||
| 223 : | while true | ||
| 224 : | do | ||
| 225 : | echo "Do you really want to quit?" | ||
| 226 : | read answer | ||
| 227 : | |||
| 228 : | case $answer in | ||
| 229 : | |||
| 230 : | y* | Y* ) return 0;; | ||
| 231 : | *) echo "Resuming..." | ||
| 232 : | return 1;; | ||
| 233 : | |||
| 234 : | esac | ||
| 235 : | |||
| 236 : | done | ||
| 237 : | } | ||
| 238 : | |||
| 239 : | ##################################################### | ||
| 240 : | # Level 1 | ||
| 241 : | ##################################################### | ||
| 242 : | |||
| 243 : | SignalHandler() | ||
| 244 : | |||
| 245 : | { | ||
| 246 : | if ReallyQuit # Call a function | ||
| 247 : | then | ||
| 248 : | exit 0 | ||
| 249 : | else | ||
| 250 : | return 0 | ||
| 251 : | fi | ||
| 252 : | } | ||
| 253 : | |||
| 254 : | ##################################################### | ||
| 255 : | # Level 0 : main program | ||
| 256 : | ##################################################### | ||
| 257 : | |||
| 258 : | trap SignalHandler 2 15 # Trap kill signals 2 and 15 | ||
| 259 : | |||
| 260 : | echo "Type some lines of text..." | ||
| 261 : | |||
| 262 : | while read text | ||
| 263 : | do | ||
| 264 : | |||
| 265 : | echo "$text - CTRL-C to exit" | ||
| 266 : | |||
| 267 : | done | ||
| 268 : | |||
| 269 : | Note that the logical tree structure of this program is upside down | ||
| 270 : | (the highest level comes at the bottom). This is because all subroutines | ||
| 271 : | must be defined before they are used. | ||
| 272 : | |||
| 273 : | This example concludes our brief survey of the Bourne shell. | ||
| 274 : | |||
| 275 : | |||
| 276 : | File: unix.info, Node: setuid setgid scripts, Next: Limitations of shell, Prev: Procedures and traps, Up: Bourne shell | ||
| 277 : | |||
| 278 : | setuid and setgid scripts | ||
| 279 : | ========================= | ||
| 280 : | |||
| 281 : | The superuser `root' is the only privileged user in UNIX. All other | ||
| 282 : | users have only restricted access to the system. Usually this is | ||
| 283 : | desirable, but sometimes it is a nuisance. | ||
| 284 : | |||
| 285 : | A setuid script is a script which has its _setuid-bit_ set. When | ||
| 286 : | such a script is executed by a user, it is run with all the rights and | ||
| 287 : | privileges of the owner of the script. All of the commands in the script | ||
| 288 : | are executed as the owner of the file and not with the user-id of the | ||
| 289 : | person who ran the script. If the owner of the setuid script is `root' | ||
| 290 : | then the commands in the script are run with _root privileges_! | ||
| 291 : | |||
| 292 : | Setuid scripts are clearly a touchy security issue. When giving away | ||
| 293 : | one's rights to another user (especially those of `root') one is | ||
| 294 : | tempting hackers. Setuid scripts should be _avoided_. | ||
| 295 : | |||
| 296 : | A setgid program is almost the same, but only the group id is set to | ||
| 297 : | that of the owner of the file. Often the effect is the same. | ||
| 298 : | |||
| 299 : | An example of a setuid program is the `ps' program. `ps' lists all | ||
| 300 : | of the processes running in the kernel. In order to do this it needs | ||
| 301 : | permission to access the private data structures in the kernel. By | ||
| 302 : | making `ps' setgid root, it allows ordinary users to be able to read as | ||
| 303 : | much as the writers of `ps' thought fit, but no more. | ||
| 304 : | |||
| 305 : | Naturally, only the superuser can make a file setuid or setgid root. | ||
| 306 : | |||
| 307 : | |||
| 308 : | File: unix.info, Node: Limitations of shell, Next: Ex4, Prev: setuid setgid scripts, Up: Bourne shell | ||
| 309 : | |||
| 310 : | Summary: Limitations of shell programming | ||
| 311 : | ========================================= | ||
| 312 : | |||
| 313 : | To summarize the last two long and oppressive chapters we shall take | ||
| 314 : | a step back from the details and look at what we have achieved. | ||
| 315 : | |||
| 316 : | The idea behind the shell is to provide a user interface, with | ||
| 317 : | access to the system's facilities at a simple level. In the 70's user | ||
| 318 : | interfaces were not deisgned to be user-friendly. The UNIX shell is | ||
| 319 : | not particularly use friendly, but it is very powerful. Perhaps it | ||
| 320 : | would have been enough to provide only commands to allow users to write | ||
| 321 : | C programs. Since all of the system functions are available from C, | ||
| 322 : | that would certainly allow everyone to do what anything that UNIX can | ||
| 323 : | do. But shell programming is much more _immediate_ than C. It is an | ||
| 324 : | environment of _frequently used tools_. Also for quick programming | ||
| 325 : | solutions: C is a compiled language, whereas the shell is an | ||
| 326 : | interpreter. A quick shell program can solve many problems in no time | ||
| 327 : | at all, without having to compile anything. | ||
| 328 : | |||
| 329 : | Shell programming is only useful for `quick and easy' programs. To | ||
| 330 : | use it for anything serious is an abuse. Programming difficult things | ||
| 331 : | in shell is clumsy, and it is difficult to get returned-information | ||
| 332 : | (like error messages) back in a useful form. Besides, shell scripts are | ||
| 333 : | slow compared to real programs since they involve starting a new | ||
| 334 : | program for each new command. | ||
| 335 : | |||
| 336 : | These difficulties are solved partly by Perl, which we shall consider | ||
| 337 : | next - but in the final analysis, real programs of substance need to be | ||
| 338 : | written in C. Contrary to popular belief, this is not more difficult | ||
| 339 : | than programming in the shell - in fact, many things are much simpler, | ||
| 340 : | because all of the shell commands originated as C functions. The shell | ||
| 341 : | is an extra layer of the UNIX onion which we have to battle our way | ||
| 342 : | through to get where we're going. | ||
| 343 : | |||
| 344 : | Sometimes it is helpful to be shielded from _low level_ details - | ||
| 345 : | sometimes it is a _hindrance_. In the remaining chapters we shall | ||
| 346 : | consider more involved programming needs. | ||
| 347 : | |||
| 348 : | |||
| 349 : | File: unix.info, Node: Ex4, Prev: Limitations of shell, Up: Bourne shell | ||
| 350 : | |||
| 351 : | Exercises | ||
| 352 : | ========= | ||
| 353 : | |||
| 354 : | 1. Write an improved `which' command in C-shell. | ||
| 355 : | |||
| 356 : | 2. Make a counter program which records in a file how many times you | ||
| 357 : | log in to your account. You can call this in your .cshrc file. | ||
| 358 : | |||
| 359 : | 3. Make a Bourne shell script to kill all the processes owned by a | ||
| 360 : | particular user. (Note, that if you are not the superuser, you | ||
| 361 : | cannot kill processes owned by other users.) | ||
| 362 : | |||
| 363 : | 4. Write a script to replace the `rm' command with something safer. | ||
| 364 : | Think about a way of implementing `rm' so that it is possible to | ||
| 365 : | get deleted files back again in case of emergencies. This is not | ||
| 366 : | possible using the normal `rm' command. Hint: save files in a | ||
| 367 : | hidden directory `.deleted'. Make your script delete files in the | ||
| 368 : | `.deleted' directory if they are older than a week, so that you | ||
| 369 : | don't fill up the disk with rubbish. | ||
| 370 : | |||
| 371 : | 5. Suppose you have a bunch of files with a particular file-extension: | ||
| 372 : | write a script in csh to change the extension to something else. | ||
| 373 : | e.g. to change *.C into *.c. Give the old and new extensions as | ||
| 374 : | arguments to the script. | ||
| 375 : | |||
| 376 : | 6. Write a program in sh to search for files in the current directory | ||
| 377 : | which contain a certain string. e.g. search for all files which | ||
| 378 : | contain the word "if". Hint: use the "find" command. | ||
| 379 : | |||
| 380 : | 7. Use the manual pages to find out about the commands `at', `batch' | ||
| 381 : | and `atq'. Test these commands by executing the shell command | ||
| 382 : | `date' at some time of your choice. Use the `-m' option so that | ||
| 383 : | the result of the job is mailed to you. | ||
| 384 : | |||
| 385 : | 8. Write a script in sh or csh to list all of the files bigger than a | ||
| 386 : | certain size starting from the current directory, and including | ||
| 387 : | all subdirectories. This kind of program is useful for system | ||
| 388 : | administrators when a disk becomes full. | ||
| 389 : | |||
| 390 : | |||
| 391 : | File: unix.info, Node: Perl, Next: WWW and CGI programming, Prev: Bourne shell, Up: Top | ||
| 392 : | |||
| 393 : | Perl | ||
| 394 : | **** | ||
| 395 : | |||
| 396 : | So far, we have been looking at shell programming for performing | ||
| 397 : | fairly simple tasks. Now let's extend the idea of shell programming to | ||
| 398 : | cover more complex tasks like systems programming and network | ||
| 399 : | communications. Perl is a language which was designed to retain the | ||
| 400 : | immediateness of shell languages, but at the same time capture some of | ||
| 401 : | the flexibility of C. Perl is an acronym for _Practical extraction and | ||
| 402 : | report language_. In this chapter, we shall not aim to teach Perl from | ||
| 403 : | scratch - the best way to learn it is to use it! Rather we shall | ||
| 404 : | concentrate on demonstrating some principles. | ||
| 405 : | |||
| 406 : | * Menu: | ||
| 407 : | |||
| 408 : | * sed awk cut paste:: | ||
| 409 : | * Perl structure:: | ||
| 410 : | * Perl variables:: | ||
| 411 : | * Loops and conditionals:: | ||
| 412 : | * Files in perl:: | ||
| 413 : | * Perl subroutines:: | ||
| 414 : | * die:: | ||
| 415 : | * stat():: | ||
| 416 : | * Perl examples:: | ||
| 417 : | * Pattern matching:: | ||
| 418 : | * search and replace:: | ||
| 419 : | * WWW example:: | ||
| 420 : | * WWW example 2:: | ||
| 421 : | * Other functions:: | ||
| 422 : | * Perl summary:: | ||
| 423 : | * Ex5:: | ||
| 424 : | * Proj5:: | ||
| 425 : | |||
| 426 : | |||
| 427 : | File: unix.info, Node: sed awk cut paste, Next: Perl structure, Prev: Perl, Up: Perl | ||
| 428 : | |||
| 429 : | Sed and awk, cut and paste | ||
| 430 : | ========================== | ||
| 431 : | |||
| 432 : | One of the reasons for using Perl is that it is extremely good at | ||
| 433 : | textfile handling-one of the most important things for UNIX users, and | ||
| 434 : | particularly useful in connection with CGI script processing on the | ||
| 435 : | World Wide Web. It has simple built-in constructs for searching and | ||
| 436 : | replacing text, storing information in arrays and retrieving them in | ||
| 437 : | sorted form. All of the these things have previously been possible using | ||
| 438 : | the UNIX shell commands | ||
| 439 : | sed | ||
| 440 : | awk | ||
| 441 : | cut | ||
| 442 : | paste | ||
| 443 : | |||
| 444 : | but these commands were designed to work primarily in the Bourne shell | ||
| 445 : | and are a bit `awk'ward to use for all but the simplest applications. | ||
| 446 : | |||
| 447 : | `sed' | ||
| 448 : | is a stream editor. It takes command line instructions, reads | ||
| 449 : | input from the stream `stdin' and produces output on _stdout_ | ||
| 450 : | according to those instructions. `sed' works line by line from the | ||
| 451 : | start of a textfile. | ||
| 452 : | |||
| 453 : | `awk' | ||
| 454 : | is a pattern matching and processing language. It takes a textfile | ||
| 455 : | and reads it line by line, matching _regular expressions_ and | ||
| 456 : | acting on them. `awk' is powerful enough to have conditional | ||
| 457 : | instructions like `if..then..else' and uses C's `printf' | ||
| 458 : | construction for output. | ||
| 459 : | |||
| 460 : | `cut' | ||
| 461 : | Takes a line of input and cuts it into _fields_, separated by some | ||
| 462 : | character. For instance, a normal line of text is a string of | ||
| 463 : | words separated by spaces. Each word is a different field. `cut' | ||
| 464 : | can be used, for instance, to pick out the third column in a | ||
| 465 : | table. Any character can be specified as the separator. | ||
| 466 : | |||
| 467 : | `paste' | ||
| 468 : | is the logical opposite of cut. It concatenates n files, and makes | ||
| 469 : | each line in the file into a column of a table. For instance, | ||
| 470 : | `paste one two three' would make a table in which the first column | ||
| 471 : | consisted of all lines in `one', the second of all lines in `two' | ||
| 472 : | and the third of all lines in `three'. If one file is longer than | ||
| 473 : | the others, then some columns have blank spaces. | ||
| 474 : | |||
| 475 : | Perl unifies all of these operations and more. It also makes them | ||
| 476 : | much simpler. | ||
| 477 : | |||
| 478 : | |||
| 479 : | File: unix.info, Node: Perl structure, Next: Perl variables, Prev: sed awk cut paste, Up: Perl | ||
| 480 : | |||
| 481 : | Program structure | ||
| 482 : | ================= | ||
| 483 : | |||
| 484 : | To summarize Perl, we need to know about the structure of a Perl | ||
| 485 : | program, the conditional constructs it has, its loops and its variables. | ||
| 486 : | In the latest versions of Perl (Perl 5), you can write object oriented | ||
| 487 : | programs of great complexity. We shall not go into this depth, for the | ||
| 488 : | simple reason that Perl's strength is not as a general programming | ||
| 489 : | language but as a specialized language for textfile handling. The | ||
| 490 : | syntax of Perl is in many ways like the C programming language, but | ||
| 491 : | there are important differences. | ||
| 492 : | |||
| 493 : | * Variables do not have _types_. They are interpreted in a context | ||
| 494 : | sensitive way. The operators which acts upon variables determine | ||
| 495 : | whether a variable is to be considered a string or as an integer | ||
| 496 : | etc. | ||
| 497 : | |||
| 498 : | * Although there are no types, Perl defines _arrays_ of different | ||
| 499 : | kinds. There are three different kinds of array, labelled by the | ||
| 500 : | symbols `$', `@' and `%'. | ||
| 501 : | |||
| 502 : | * Perl keeps a number of standard variables with special names e.g. | ||
| 503 : | `$_ @ARGV' and `%ENV'. Special attention should be paid to these. | ||
| 504 : | They are very important! | ||
| 505 : | |||
| 506 : | * The shell reverse apostrophe notation ``command`' can be used to | ||
| 507 : | execute UNIX programs and get the result into a Perl variable. | ||
| 508 : | |||
| 509 : | |||
| 510 : | Here is a simple `structured hello world' program in Perl. Notice | ||
| 511 : | that subroutines are called using the `&' symbol. There is no special | ||
| 512 : | way of marking the main program - it is simply that part of the program | ||
| 513 : | which starts at line 1. | ||
| 514 : | |||
| 515 : | #!/local/bin/perl | ||
| 516 : | # | ||
| 517 : | # Comments | ||
| 518 : | # | ||
| 519 : | |||
| 520 : | &Hello(); | ||
| 521 : | &World; | ||
| 522 : | |||
| 523 : | # end of main | ||
| 524 : | |||
| 525 : | sub Hello | ||
| 526 : | { | ||
| 527 : | print "Hello"; | ||
| 528 : | } | ||
| 529 : | |||
| 530 : | |||
| 531 : | sub World | ||
| 532 : | { | ||
| 533 : | print "World\n"; | ||
| 534 : | } | ||
| 535 : | |||
| 536 : | The parentheses on subroutines are optional, if there are no parameters | ||
| 537 : | passed. Notice that each line must end in a semi-colon. | ||
| 538 : | |||
| 539 : | |||
| 540 : | File: unix.info, Node: Perl variables, Next: Loops and conditionals, Prev: Perl structure, Up: Perl | ||
| 541 : | |||
| 542 : | Perl variables | ||
| 543 : | ============== | ||
| 544 : | |||
| 545 : | * Menu: | ||
| 546 : | |||
| 547 : | * Scalar variables:: | ||
| 548 : | * The default scalar variable:: | ||
| 549 : | * Array variables:: | ||
| 550 : | * Array commands:: | ||
| 551 : | * Associated arrays:: | ||
| 552 : | * Array example:: | ||
| 553 : | |||
| 554 : | |||
| 555 : | File: unix.info, Node: Scalar variables, Next: The default scalar variable, Prev: Perl variables, Up: Perl variables | ||
| 556 : | |||
| 557 : | Scalar variables | ||
| 558 : | ---------------- | ||
| 559 : | |||
| 560 : | In Perl, variables do not have to be declared before they are used. | ||
| 561 : | Whenever you use a new symbol, Perl automatically adds the symbol to | ||
| 562 : | its symbol table and initializes the variable to the empty string. | ||
| 563 : | |||
| 564 : | It is important to understand that there is no practical difference | ||
| 565 : | between zero and the empty string in perl - except in the way that you, | ||
| 566 : | the user, choose to use it. Perl makes no distinction between strings | ||
| 567 : | and integers or any other types of data - except when it wants to | ||
| 568 : | interpret them. For instance, to compare two variables as strings is | ||
| 569 : | not the same as comparing them as integers, even if the string contains | ||
| 570 : | a textual representation of an integer. Take a look at the following | ||
| 571 : | program. | ||
| 572 : | |||
| 573 : | #!/local/bin/perl | ||
| 574 : | # | ||
| 575 : | # Nothing! | ||
| 576 : | # | ||
| 577 : | |||
| 578 : | print "Nothing == $nothing\n"; | ||
| 579 : | |||
| 580 : | print "Nothing is zero!\n" if ($nothing == 0); | ||
| 581 : | |||
| 582 : | if ($nothing eq "") | ||
| 583 : | { | ||
| 584 : | print STDERR "Nothing is really nothing!\n"; | ||
| 585 : | } | ||
| 586 : | |||
| 587 : | $nothing = 0; | ||
| 588 : | |||
| 589 : | print "Nothing is now $nothing\n"; | ||
| 590 : | |||
| 591 : | The output from this program is | ||
| 592 : | |||
| 593 : | |||
| 594 : | Nothing == | ||
| 595 : | Nothing is zero! | ||
| 596 : | Nothing is really nothing! | ||
| 597 : | Nothing is now 0 | ||
| 598 : | |||
| 599 : | There are several important things to note here. First of all, we | ||
| 600 : | never declare the variable `nothing'. When we try to write its value, | ||
| 601 : | perl creates the name and associates a NULL value to it i.e. the empty | ||
| 602 : | string. There is no error. Perl knows it is a variable because of the | ||
| 603 : | `$' symbol in front of it. All _scalar_ variables are identified by | ||
| 604 : | using the dollar symbol. | ||
| 605 : | |||
| 606 : | Next, we compare the value of `$nothing' to the integer `0' using | ||
| 607 : | the integer comparison symbol `==', and then we compare it to the empty | ||
| 608 : | string using the string comparison symbol `eq'. Both tests are true! | ||
| 609 : | That means that the empty string is interpreted as having a numerical | ||
| 610 : | value of zero. In fact _any string_ which does not form a valid integer | ||
| 611 : | number has a numerical value of zero. | ||
| 612 : | |||
| 613 : | Finally we can set `$nothing' explicitly to a valid integer string | ||
| 614 : | zero, which would now pass the first test, but fail the second. | ||
| 615 : | |||
| 616 : | As extra spice, this program also demonstrates two different ways of | ||
| 617 : | writing the `if' command in perl. | ||
| 618 : | |||
| 619 : | |||
| 620 : | File: unix.info, Node: The default scalar variable, Next: Array variables, Prev: Scalar variables, Up: Perl variables | ||
| 621 : | |||
| 622 : | The default scalar variable. | ||
| 623 : | ---------------------------- | ||
| 624 : | |||
| 625 : | The special variable `$_' is used for many purposes in Perl. It is | ||
| 626 : | used as a buffer to contain the result of the last operation, the last | ||
| 627 : | line read in from a file etc. It is so general that many functions | ||
| 628 : | which act on scalar variables work by default on `$_' if no other | ||
| 629 : | argument is specified. For example, | ||
| 630 : | print; | ||
| 631 : | |||
| 632 : | is the same as | ||
| 633 : | print $_; | ||
| 634 : | |||
| 635 : | |||
| 636 : | File: unix.info, Node: Array variables, Next: Array commands, Prev: The default scalar variable, Up: Perl variables | ||
| 637 : | |||
| 638 : | Array (vector) variables | ||
| 639 : | ------------------------ | ||
| 640 : | |||
| 641 : | The complement of scalar variables is arrays. An array, in Perl is | ||
| 642 : | identified by the `@' symbol and, like scalar variables, is allocated | ||
| 643 : | and initialized dynamically. | ||
| 644 : | |||
| 645 : | @array[0] = "This little piggy went to market"; | ||
| 646 : | @array[2] = "This little piggy stayed at home"; | ||
| 647 : | |||
| 648 : | print "@array[0] @array[1] @array[2]"; | ||
| 649 : | |||
| 650 : | The index of an array is always understood to be a number, not a | ||
| 651 : | string, so if you use a non-numerical string to refer to an array | ||
| 652 : | element, you will always get the zeroth element, since a non-numerical | ||
| 653 : | string has an integer value of zero. | ||
| 654 : | |||
| 655 : | An important array which every program defines is | ||
| 656 : | @ARGV | ||
| 657 : | |||
| 658 : | This is the argument vector array, and contains the commands line | ||
| 659 : | arguments by analogy with the C-shell variable `$argv[]'. | ||
| 660 : | |||
| 661 : | Given an array, we can find the last element by using the `$#' | ||
| 662 : | operator. For example, | ||
| 663 : | $last_element = $ARGV[$#ARGV]; | ||
| 664 : | |||
| 665 : | Notice that each element in an array is a scalar variable. The `$#' | ||
| 666 : | cannot be interpreted directly as the number of elements in the array, | ||
| 667 : | as it can in the C-shell. You should experiment with the value of this | ||
| 668 : | quantity - it often necessary to add 1 or 2 to its value in order to | ||
| 669 : | get the behaviour one is used to in the C-shell. | ||
| 670 : | |||
| 671 : | Perl does not support multiple-dimension arrays directly, but it is | ||
| 672 : | possible to simulate them yourself. (See the Perl book.) | ||
| 673 : | |||
| 674 : | |||
| 675 : | File: unix.info, Node: Array commands, Next: Associated arrays, Prev: Array variables, Up: Perl variables | ||
| 676 : | |||
| 677 : | Special array commands | ||
| 678 : | ---------------------- | ||
| 679 : | |||
| 680 : | The `shift' command acts on arrays and returns and removes the first | ||
| 681 : | element of the array. Afterwards, all of the elements are shifted down | ||
| 682 : | one place. So one way to read the elements of an array in order is to | ||
| 683 : | repeatedly call `shift'. | ||
| 684 : | |||
| 685 : | $next_element=shift(@myarray); | ||
| 686 : | |||
| 687 : | Note that, if the array argument is omitted, then `shift' works on | ||
| 688 : | `@ARGV' by default. | ||
| 689 : | |||
| 690 : | Another useful function is `split', which takes a string and turns | ||
| 691 : | it into an array of strings. `split' works by choosing a character | ||
| 692 : | (usually a space) to delimit the array elements, so a string containing | ||
| 693 : | a sentence separated by spaces would be turned into an array of words. | ||
| 694 : | The syntax is | ||
| 695 : | |||
| 696 : | @array = split; # works with spaces on $_ | ||
| 697 : | @array = split(pattern,string); # Breaks on pattern | ||
| 698 : | ($v1,$v2...) = split(pattern,string); # Name array elements with scalars | ||
| 699 : | |||
| 700 : | In the first of these cases, it is assumed that the variable `$_' is to | ||
| 701 : | be split on whitespace characters. In the second case, we decide on | ||
| 702 : | what characterthe split is to take place and on what string the | ||
| 703 : | function is to act. For instance | ||
| 704 : | |||
| 705 : | @new_array = split(":","name:passwd:uid:gid:gcos:home:shell"); | ||
| 706 : | |||
| 707 : | The result is a seven element array called `@new_array', where | ||
| 708 : | `$new_array[0]' is `name' etc. | ||
| 709 : | |||
| 710 : | In the final example, the left hand side shows that we wish to capture | ||
| 711 : | elements of the array in a named set of scalar variables. If the | ||
| 712 : | number of variables on the lefthand side is fewer than the number of | ||
| 713 : | strings which are generated on the right hand side, they are discarded. | ||
| 714 : | If the number on the left hand side is greater, then the remainder | ||
| 715 : | variables are empty. | ||
| 716 : | |||
| 717 : | |||
| 718 : | File: unix.info, Node: Associated arrays, Next: Array example, Prev: Array commands, Up: Perl variables | ||
| 719 : | |||
| 720 : | Associated arrays | ||
| 721 : | ----------------- | ||
| 722 : | |||
| 723 : | One of the very nice features of Perl is the ability to use one | ||
| 724 : | string as an index to another string in an array. For example, we can | ||
| 725 : | make a short encyclopaedia of zoo animals by constructing an | ||
| 726 : | associative array in which the keys (or indices) of the array are the | ||
| 727 : | names of animals, and the contents of the array are the information | ||
| 728 : | about them. | ||
| 729 : | |||
| 730 : | |||
| 731 : | $animals{"Penguin"} = "A suspicious animal, good with cheese crackers..."; | ||
| 732 : | $animals{"dog"} = "Plays stupid, but could be a cover..."; | ||
| 733 : | |||
| 734 : | if ($index eq "fish") | ||
| 735 : | { | ||
| 736 : | $animals{$index} = "Often comes in square boxes. Very cold."; | ||
| 737 : | } | ||
| 738 : | |||
| 739 : | An entire associated array is written `%array', while the elements are | ||
| 740 : | `$array{$key}'. | ||
| 741 : | |||
| 742 : | Perl provides a special associative array for every program called | ||
| 743 : | `%ENV'. This contains the _environment variables_ defined in the parent | ||
| 744 : | shell which is running the Perl program. For example | ||
| 745 : | print "Username = $ENV{"USER"}\n"; | ||
| 746 : | |||
| 747 : | $ld = "LD_LIBRARY_PATH"; | ||
| 748 : | print "The link editor path is $ENV{$ld}\n"; | ||
| 749 : | |||
| 750 : | To get the current path into an ordinary array, one could write, | ||
| 751 : | @path_array= split(":",$ENV{"PATH"}); | ||
| 752 : | |||
| 753 : | |||
| 754 : | File: unix.info, Node: Array example, Prev: Associated arrays, Up: Perl variables | ||
| 755 : | |||
| 756 : | Array example program | ||
| 757 : | --------------------- | ||
| 758 : | |||
| 759 : | Here is an example which prints out a list of files in a specified | ||
| 760 : | directory, in order of their UNIX protection bits. The _least_ | ||
| 761 : | protected file files come first. | ||
| 762 : | |||
| 763 : | #!/local/bin/perl | ||
| 764 : | # | ||
| 765 : | # Demonstration of arrays and associated arrays. | ||
| 766 : | # Print out a list of files, sorted by protection, | ||
| 767 : | # so that the least secure files come first. | ||
| 768 : | # | ||
| 769 : | # e.g. arrays <list of words> | ||
| 770 : | # arrays *.C | ||
| 771 : | # | ||
| 772 : | ############################################################ | ||
| 773 : | |||
| 774 : | |||
| 775 : | print "You typed in ",$#ARGV+1," arguments to command\n"; | ||
| 776 : | |||
| 777 : | if ($#ARGV < 1) | ||
| 778 : | { | ||
| 779 : | print "That's not enough to do anything with!\n"; | ||
| 780 : | } | ||
| 781 : | |||
| 782 : | while ($next_arg = shift(@ARGV)) | ||
| 783 : | { | ||
| 784 : | if ( ! ( -f $next_arg || -d $next_arg)) | ||
| 785 : | { | ||
| 786 : | print "No such file: $next_arg\n"; | ||
| 787 : | next; | ||
| 788 : | } | ||
| 789 : | |||
| 790 : | ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size) = stat($next_arg); | ||
| 791 : | $octalmode = sprintf("%o",$mode & 0777); | ||
| 792 : | |||
| 793 : | $assoc_array{$octalmode} .= $next_arg. | ||
| 794 : | " : size (".$size."), mode (".$octalmode.")\n"; | ||
| 795 : | } | ||
| 796 : | |||
| 797 : | print "In order: LEAST secure first!\n\n"; | ||
| 798 : | |||
| 799 : | foreach $i (reverse sort keys(%assoc_array)) | ||
| 800 : | { | ||
| 801 : | print $assoc_array{$i}; | ||
| 802 : | } | ||
| 803 : | |||
| 804 : | |||
| 805 : | File: unix.info, Node: Loops and conditionals, Next: Files in perl, Prev: Perl variables, Up: Perl | ||
| 806 : | |||
| 807 : | Loops and conditionals | ||
| 808 : | ====================== | ||
| 809 : | |||
| 810 : | Here are some of the most commonly used decision-making | ||
| 811 : | constructions and loops in Perl. The following is not a comprehensive | ||
| 812 : | list - for that, you will have to look in the Perl bible: _Programming | ||
| 813 : | Perl_, by Larry Wall and Randal Schwartz. The basic pattern follows the | ||
| 814 : | C programming language quite closely. In the case of the `for' loop, | ||
| 815 : | Perl has both the C-like version, called `for' and a `foreach' command | ||
| 816 : | which is like the C-shell implementation. | ||
| 817 : | |||
| 818 : | if (EXPRESSION) | ||
| 819 : | { | ||
| 820 : | block; | ||
| 821 : | } | ||
| 822 : | else | ||
| 823 : | { | ||
| 824 : | block; | ||
| 825 : | } | ||
| 826 : | |||
| 827 : | command if (EXPRESSION); | ||
| 828 : | |||
| 829 : | unless (EXPRESSION) | ||
| 830 : | { | ||
| 831 : | block; | ||
| 832 : | } | ||
| 833 : | else | ||
| 834 : | { | ||
| 835 : | block; | ||
| 836 : | } | ||
| 837 : | |||
| 838 : | while (EXPRESSION) | ||
| 839 : | { | ||
| 840 : | block; | ||
| 841 : | } | ||
| 842 : | |||
| 843 : | do | ||
| 844 : | { | ||
| 845 : | block; | ||
| 846 : | } | ||
| 847 : | while (EXPRESSION); | ||
| 848 : | |||
| 849 : | for (INITIALIZER; EXPRESSION; STATEMENT) | ||
| 850 : | { | ||
| 851 : | block; | ||
| 852 : | } | ||
| 853 : | |||
| 854 : | foreach VARIABLE(ARRAY) | ||
| 855 : | { | ||
| 856 : | block; | ||
| 857 : | } | ||
| 858 : | |||
| 859 : | In all cases, the `else' clauses may be omitted. | ||
| 860 : | |||
| 861 : | Strangely, perl does not have a `switch' statement, but the Perl book | ||
| 862 : | describes how to make one using the features provided. | ||
| 863 : | |||
| 864 : | * Menu: | ||
| 865 : | |||
| 866 : | * The for loop:: | ||
| 867 : | * The foreach loop:: | ||
| 868 : | * Iterating over elements in arrays:: | ||
| 869 : | * Iterating over lines in a file:: | ||
| 870 : | |||
| 871 : | |||
| 872 : | File: unix.info, Node: The for loop, Next: The foreach loop, Prev: Loops and conditionals, Up: Loops and conditionals | ||
| 873 : | |||
| 874 : | The for loop | ||
| 875 : | ------------ | ||
| 876 : | |||
| 877 : | The for loop is exactly like that in C or C++ and is used to iterate | ||
| 878 : | over a numerical index, like this: | ||
| 879 : | |||
| 880 : | |||
| 881 : | for ($i = 0; $i < 10; $i++) | ||
| 882 : | { | ||
| 883 : | print $i, "\n"; | ||
| 884 : | } | ||
| 885 : | |||
| 886 : | |||
| 887 : | File: unix.info, Node: The foreach loop, Next: Iterating over elements in arrays, Prev: The for loop, Up: Loops and conditionals | ||
| 888 : | |||
| 889 : | The foreach loop | ||
| 890 : | ---------------- | ||
| 891 : | |||
| 892 : | The foreach loop is like its counterpart in the C shell. It is used | ||
| 893 : | for reading elements one by one from a regular array. For example, | ||
| 894 : | |||
| 895 : | |||
| 896 : | foreach $i ( @array ) | ||
| 897 : | { | ||
| 898 : | print $i, "\n"; | ||
| 899 : | } | ||
| 900 : | |||
| 901 : | |||
| 902 : | File: unix.info, Node: Iterating over elements in arrays, Next: Iterating over lines in a file, Prev: The foreach loop, Up: Loops and conditionals | ||
| 903 : | |||
| 904 : | Iterating over elements in arrays | ||
| 905 : | --------------------------------- | ||
| 906 : | |||
| 907 : | One of the main uses for `for' type loops is to iterate over | ||
| 908 : | successive values in an array. This can be done in two ways which show | ||
| 909 : | the essential difference between `for' and `foreach'. | ||
| 910 : | |||
| 911 : | If we want to fetch each value in an array in turn, without caring | ||
| 912 : | about numerical indices, the it is simpest to use the `foreach' loop. | ||
| 913 : | |||
| 914 : | |||
| 915 : | @array = split(" ","a b c d e f g"); | ||
| 916 : | |||
| 917 : | foreach $var ( @array ) | ||
| 918 : | { | ||
| 919 : | print $var, "\n"; | ||
| 920 : | } | ||
| 921 : | |||
| 922 : | This example prints each letter on a separate line. If, on the other | ||
| 923 : | hand, we are interested in the index, for the purposes of some | ||
| 924 : | calculation, then the `for' loop is preferable. | ||
| 925 : | |||
| 926 : | |||
| 927 : | @array = split(" ","a b c d e f g"); | ||
| 928 : | |||
| 929 : | for ($i = 0; $i <= $#array; $i++) | ||
| 930 : | { | ||
| 931 : | print $array[$i], "\n"; | ||
| 932 : | } | ||
| 933 : | |||
| 934 : | Notice that, unlike the for-loop idiom in C/C++, the limit is `$i <= | ||
| 935 : | $#array', i.e. `less than or equal to' rather than `less than'. This is | ||
| 936 : | because the `$#' operator does not return the number of elements in the | ||
| 937 : | array but rather the last element. | ||
| 938 : | |||
| 939 : | Associated arrays are slightly different, since they do not use | ||
| 940 : | numerical keys. Instead they use a set of strings, like in a database, | ||
| 941 : | so that you can use one string to look up another. In order to iterate | ||
| 942 : | over the values in the array we need to get a list of these strings. | ||
| 943 : | The `keys' command is used for this. | ||
| 944 : | |||
| 945 : | $assoc{"mark"} = "cool"; | ||
| 946 : | $assoc{"GNU"} = "brave"; | ||
| 947 : | $assoc{"zebra"} = "stripy"; | ||
| 948 : | |||
| 949 : | foreach $var ( keys %assoc ) | ||
| 950 : | { | ||
| 951 : | print "$var , $assoc{$var} \n"; | ||
| 952 : | } | ||
| 953 : | |||
| 954 : | The order of the keys is not defined in the above example, but you can | ||
| 955 : | choose to sort them alphabetically by writing | ||
| 956 : | |||
| 957 : | foreach $var ( sort keys %assoc ) | ||
| 958 : | |||
| 959 : | instead. | ||
| 960 : | |||
| 961 : | |||
| 962 : | File: unix.info, Node: Iterating over lines in a file, Prev: Iterating over elements in arrays, Up: Loops and conditionals | ||
| 963 : | |||
| 964 : | Iterating over lines in a file | ||
| 965 : | ------------------------------ | ||
| 966 : | |||
| 967 : | Since Perl is about file handling we are very interested in reading | ||
| 968 : | files. Unlike C and C++, perl likes to read files line by line. The | ||
| 969 : | angle brackets are used for this, *Note Files in perl::. Assuming that | ||
| 970 : | we have some file handle `<file>', for instance `<STDIN>', we can | ||
| 971 : | always read the file line by line with a while-loop like this. | ||
| 972 : | |||
| 973 : | |||
| 974 : | while ($line = <file>) | ||
| 975 : | { | ||
| 976 : | print $line; | ||
| 977 : | } | ||
| 978 : | |||
| 979 : | Note that `$line' includes the end of line character on the end of each | ||
| 980 : | line. If you want to remove it, you should add a `chop' command: | ||
| 981 : | |||
| 982 : | |||
| 983 : | while ($line = <file>) | ||
| 984 : | { | ||
| 985 : | chop $line; | ||
| 986 : | print "line = ($line)\n"; | ||
| 987 : | } | ||
| 988 : | |||
| 989 : | |||
| 990 : | File: unix.info, Node: Files in perl, Next: Perl subroutines, Prev: Loops and conditionals, Up: Perl | ||
| 991 : | |||
| 992 : | Files in perl | ||
| 993 : | ============= | ||
| 994 : | |||
| 995 : | Opening files is straightforward in Perl. Files must be opened and | ||
| 996 : | closed using - wait for it - the commands `open' and `close'. You | ||
| 997 : | should be careful to close files after you have finished with them - | ||
| 998 : | especially if you are writing _to_ a file. Files are buffered and often | ||
| 999 : | large parts of a file are not actually written until the `close' | ||
| 1000 : | command is received. | ||
| 1001 : | |||
| 1002 : | Three files are, of course, always open for every program, namely | ||
| 1003 : | `STDIN', `STDOUT'and `STDERR'. | ||
| 1004 : | |||
| 1005 : | Formally, to open a file, we must obtain a file descriptor or file | ||
| 1006 : | handle. This is done using `open'; | ||
| 1007 : | |||
| 1008 : | open (file_descrip,"Filename"); | ||
| 1009 : | |||
| 1010 : | The angular brackets `<..>' are used to read from the file. For | ||
| 1011 : | example, | ||
| 1012 : | |||
| 1013 : | $line = <file_descrip>; | ||
| 1014 : | |||
| 1015 : | reads one line from the file associated with `file_descrip'. | ||
| 1016 : | |||
| 1017 : | Let's look at some examples of filing opening. Here is how we can | ||
| 1018 : | implement UNIX's `cut' and `paste' commands in perl: | ||
| 1019 : | |||
| 1020 : | #!/local/bin/perl | ||
| 1021 : | # | ||
| 1022 : | # Cut in perl | ||
| 1023 : | # | ||
| 1024 : | |||
| 1025 : | |||
| 1026 : | # Cut second column | ||
| 1027 : | |||
| 1028 : | while (<>) | ||
| 1029 : | { | ||
| 1030 : | @cut_array = split; | ||
| 1031 : | |||
| 1032 : | print "@cut_array[1]\n"; | ||
| 1033 : | } | ||
| 1034 : | |||
| 1035 : | This is the simplest way to open a file. The empty file descriptor `<>' | ||
| 1036 : | tells perl to take the argument of the command as a filename and open | ||
| 1037 : | that file for reading. This is really short for `while($_=<STDIN>)' | ||
| 1038 : | with the standard input redirected to the named file. | ||
| 1039 : | |||
| 1040 : | The `paste'program can be written as follows: | ||
| 1041 : | |||
| 1042 : | #!/local/bin/perl | ||
| 1043 : | # | ||
| 1044 : | # Paste in perl | ||
| 1045 : | # | ||
| 1046 : | # Two files only, syntax : paste file 1file2 | ||
| 1047 : | # | ||
| 1048 : | |||
| 1049 : | open (file1,"@ARGV[0]") || die "Can't open @ARGV[0]\n"; | ||
| 1050 : | open (file2,"@ARGV[1]") || die "Can't open @ARGV[1]\n"; | ||
| 1051 : | |||
| 1052 : | while (($line1 = <file1>) || ($line2 = <file2>)) | ||
| 1053 : | { | ||
| 1054 : | chop $line1; | ||
| 1055 : | chop $line2; | ||
| 1056 : | |||
| 1057 : | print "$line1 $line2\n"; # tab character between | ||
| 1058 : | } | ||
| 1059 : | |||
| 1060 : | Here we see more formally how to read from two separate files at the | ||
| 1061 : | same time. Notice that, by putting the read commands into the | ||
| 1062 : | test-expression for the `while' loop, we are using the fact that `<..>' | ||
| 1063 : | returns a non-zero (true) value unless we have reached the end of the | ||
| 1064 : | file. | ||
| 1065 : | |||
| 1066 : | To write and append to files, we use the shell redirection symbols | ||
| 1067 : | inside the `open' command. | ||
| 1068 : | open(fd,"> filename"); # open file for writing | ||
| 1069 : | open(fd,">> filename"); # open file for appending | ||
| 1070 : | |||
| 1071 : | We can also open a pipe from an arbitrary UNIX command and receive the | ||
| 1072 : | output of that command as our input: | ||
| 1073 : | open (fd,"/bin/ps aux | "); | ||
| 1074 : | |||
| 1075 : | * Menu: | ||
| 1076 : | |||
| 1077 : | * Simplest perl program:: | ||
| 1078 : | * == and eq:: | ||
| 1079 : | * chop:: | ||
| 1080 : | |||
| 1081 : | |||
| 1082 : | File: unix.info, Node: Simplest perl program, Next: == and eq, Prev: Files in perl, Up: Files in perl | ||
| 1083 : | |||
| 1084 : | A simple perl program | ||
| 1085 : | --------------------- | ||
| 1086 : | |||
| 1087 : | Let us now write the simplest perl program which illustrates the way | ||
| 1088 : | in which perl can save time. We shall write it in three different ways | ||
| 1089 : | to show what the short cuts mean. Let us implement the `cat' command, | ||
| 1090 : | which copies files to the standard output. The simplest way to write | ||
| 1091 : | this is perl is the following: | ||
| 1092 : | |||
| 1093 : | |||
| 1094 : | #!/local/bin/perl | ||
| 1095 : | |||
| 1096 : | while (<>) | ||
| 1097 : | { | ||
| 1098 : | print; | ||
| 1099 : | } | ||
| 1100 : | |||
| 1101 : | Here we have made heavy use of the many default assumptions which perl | ||
| 1102 : | makes. The program is simple, but difficult to understand for novices. | ||
| 1103 : | First of all we use the default file handle `<>' which means, take one | ||
| 1104 : | line of input from a default file. This object returns true as long as | ||
| 1105 : | it has not reached the end of the file, so this loop continues to read | ||
| 1106 : | lines until it reaches the end of file. The default file is standard | ||
| 1107 : | input, unless this script is invoked with a command line argument, in | ||
| 1108 : | which case the argument is treated as a filename and perl attempts to | ||
| 1109 : | open the argument-filename for reading. The `print' statement has no | ||
| 1110 : | argument telling it what to print, but perl takes this to mean: print | ||
| 1111 : | the default variable `$_'. | ||
| 1112 : | |||
| 1113 : | We can therefore write this more explicitly as follows: | ||
| 1114 : | |||
| 1115 : | |||
| 1116 : | #!/local/bin/perl | ||
| 1117 : | |||
| 1118 : | open (HANDLE,"$ARGV[1]"); | ||
| 1119 : | |||
| 1120 : | while (<HANDLE>) | ||
| 1121 : | { | ||
| 1122 : | print $_; | ||
| 1123 : | } | ||
| 1124 : | |||
| 1125 : | Here we have simply filled in the assumptions explicitly. The command | ||
| 1126 : | `<HANDLE>' now reads a single line from the named file-handle into the | ||
| 1127 : | default variable `$_'. To make this program more general, we can | ||
| 1128 : | elimiate the defaults entirely. | ||
| 1129 : | |||
| 1130 : | |||
| 1131 : | #!/local/bin/perl | ||
| 1132 : | |||
| 1133 : | open (HANDLE,"$ARGV[1]"); | ||
| 1134 : | |||
| 1135 : | while ($line=<HANDLE>) | ||
| 1136 : | { | ||
| 1137 : | print $line; | ||
| 1138 : | } | ||
| 1139 : | |||
| 1140 : | |||
| 1141 : | File: unix.info, Node: == and eq, Next: chop, Prev: Simplest perl program, Up: Files in perl | ||
| 1142 : | |||
| 1143 : | == and `eq' | ||
| 1144 : | ----------- | ||
| 1145 : | |||
| 1146 : | Be careful to distinguish between the comparison operator for | ||
| 1147 : | integers `==' and the corresponding operator for strings `eq'. These do | ||
| 1148 : | not work in each other's places so if you get the wrong comparison | ||
| 1149 : | operator your program might not work and it is quite difficult to find | ||
| 1150 : | the error. | ||
| 1151 : | |||
| 1152 : | |||
| 1153 : | File: unix.info, Node: chop, Prev: == and eq, Up: Files in perl | ||
| 1154 : | |||
| 1155 : | chop | ||
| 1156 : | ---- | ||
| 1157 : | |||
| 1158 : | The command `chop' cuts off the last character of a string. This is | ||
| 1159 : | useful for removing newline characters when reading files etc. The | ||
| 1160 : | syntax is | ||
| 1161 : | chop; # chop $_; | ||
| 1162 : | |||
| 1163 : | chop $scalar; # remove last character in $scalar | ||
| 1164 : | |||
| 1165 : | |||
| 1166 : | File: unix.info, Node: Perl subroutines, Next: die, Prev: Files in perl, Up: Perl | ||
| 1167 : | |||
| 1168 : | Perl subroutines | ||
| 1169 : | ================ | ||
| 1170 : | |||
| 1171 : | Subroutines are indicated, as in the example above, by the ampersand | ||
| 1172 : | `&' symbol. When parameters are passed to a Perl subroutine, they are | ||
| 1173 : | handed over as an array called `@_'. Which is analogous to the `$_' | ||
| 1174 : | variable. Here is a simple example: | ||
| 1175 : | |||
| 1176 : | #!/local/bin/perl | ||
| 1177 : | |||
| 1178 : | $a="silver"; | ||
| 1179 : | $b="gold"; | ||
| 1180 : | |||
| 1181 : | &PrintArgs($a,$b); | ||
| 1182 : | |||
| 1183 : | # end of main | ||
| 1184 : | |||
| 1185 : | sub PrintArgs | ||
| 1186 : | |||
| 1187 : | { | ||
| 1188 : | ($local_a,$local_b) = @_; | ||
| 1189 : | |||
| 1190 : | print "$local_a, $local_b\n"; | ||
| 1191 : | } | ||
| 1192 : | |||
| 1193 : | |||
| 1194 : | File: unix.info, Node: die, Next: stat(), Prev: Perl subroutines, Up: Perl | ||
| 1195 : | |||
| 1196 : | die - exit on error | ||
| 1197 : | =================== | ||
| 1198 : | |||
| 1199 : | When a program has to quit and give a message, the `die' command is | ||
| 1200 : | normally used. If called without an argument, Perl generates its own | ||
| 1201 : | message including a line number at which the error occurred. To include | ||
| 1202 : | your own message, you write | ||
| 1203 : | |||
| 1204 : | die "My message...."; | ||
| 1205 : | |||
| 1206 : | If the string is terminated with a `\n' newline character, the line | ||
| 1207 : | number of the error is not printed, otherwise Perl appends the line | ||
| 1208 : | number to your string. | ||
| 1209 : | |||
| 1210 : | When opening files, it is common to see the syntax: | ||
| 1211 : | open (filehandle,"Filename") || die "Can't open..."; | ||
| 1212 : | |||
| 1213 : | The logical `OR' symbol is used, because `open' returns true if all | ||
| 1214 : | goes well, in which case the right hand side is never evaluated. If | ||
| 1215 : | `open' is false, then die is executed. You can decide for yourself | ||
| 1216 : | whether or not you think this is good programming style - we mention it | ||
| 1217 : | here because it is common practice. | ||
| 1218 : | |||
| 1219 : | |||
| 1220 : | File: unix.info, Node: stat(), Next: Perl examples, Prev: die, Up: Perl | ||
| 1221 : | |||
| 1222 : | The `stat()' idiom | ||
| 1223 : | ================== | ||
| 1224 : | |||
| 1225 : | The unix library function `stat()' is used to find out information | ||
| 1226 : | about a given file. This function is available both in C and in Perl. | ||
| 1227 : | In perl, it returns an array of values. Usually we are interested in | ||
| 1228 : | knowing the access permissions of a file. `stat()' is called using the | ||
| 1229 : | syntax | ||
| 1230 : | |||
| 1231 : | |||
| 1232 : | @array = stat ("FILENAME"); | ||
| 1233 : | |||
| 1234 : | or alternatively, using a named array | ||
| 1235 : | |||
| 1236 : | |||
| 1237 : | ($device,$inode,$mode) = stat("FILENAME"); | ||
| 1238 : | |||
| 1239 : | The value returned in the MODE variable is a bit-pattern, *Note | ||
| 1240 : | Protection bits::. The most useful way of treating these bit patterns | ||
| 1241 : | is to use octal numbers to interpret their meaning. | ||
| 1242 : | |||
| 1243 : | To find out whether a file is readable or writable to a group of | ||
| 1244 : | users, we use a programming idiom which is very common for dealing with | ||
| 1245 : | bit patterns: first we define a mask which zeroes out all of the bits | ||
| 1246 : | in the mode string except those which we are specifically interested | ||
| 1247 : | in. This is done by defining a mask value in which the bits we want are | ||
| 1248 : | set to 1 and all others are set to zero. Then we AND the mask with the | ||
| 1249 : | mode string. If the result is different from zero then we know that all | ||
| 1250 : | of the bits were also set in the mode string. As in C, the bitwise AND | ||
| 1251 : | operator in perl is called `&'. | ||
| 1252 : | |||
| 1253 : | For example, to test whether a file is writable to other users in | ||
| 1254 : | the same group as the file, we would write the following. | ||
| 1255 : | |||
| 1256 : | |||
| 1257 : | $mask = 020; # Leading 0 means octal number | ||
| 1258 : | |||
| 1259 : | ($device,$inode,$mode) = stat("FILE"); | ||
| 1260 : | |||
| 1261 : | if ($mode & $mask) | ||
| 1262 : | { | ||
| 1263 : | print "File is writable by the group\n"; | ||
| 1264 : | } | ||
| 1265 : | |||
| 1266 : | Here the 2 in the second octal number means "write", the fact that it | ||
| 1267 : | is the second octal number from the right means that it refers to | ||
| 1268 : | "group". Thus the result of the if-test is only true if that particular | ||
| 1269 : | bit is true. We shall see this idiom in action below. | ||
| 1270 : | |||
| 1271 : | |||
| 1272 : | File: unix.info, Node: Perl examples, Next: Pattern matching, Prev: stat(), Up: Perl | ||
| 1273 : | |||
| 1274 : | Perl example programs | ||
| 1275 : | ===================== | ||
| 1276 : | |||
| 1277 : | * Menu: | ||
| 1278 : | |||
| 1279 : | * Passwd example program:: | ||
| 1280 : | * Fork example:: | ||
| 1281 : | * Database example:: | ||
| 1282 : | |||
| 1283 : | |||
| 1284 : | File: unix.info, Node: Passwd example program, Next: Fork example, Prev: Perl examples, Up: Perl examples | ||
| 1285 : | |||
| 1286 : | The passwd program and `crypt()' function | ||
| 1287 : | ----------------------------------------- | ||
| 1288 : | |||
| 1289 : | Here is a simple implementation of the UNIX `passwd' program in Perl. | ||
| 1290 : | |||
| 1291 : | #!/local/bin/perl | ||
| 1292 : | # | ||
| 1293 : | # A perl version of the passwd program. | ||
| 1294 : | # | ||
| 1295 : | # Note - the real passwd program needs to be much more | ||
| 1296 : | # secure than this one. This is just to demonstrate the | ||
| 1297 : | # use of the crypt() function. | ||
| 1298 : | # | ||
| 1299 : | ############################################################# | ||
| 1300 : | |||
| 1301 : | print "Changing passwd for $ENV{'USER'} on $ENV{'HOST'}\n"; | ||
| 1302 : | |||
| 1303 : | |||
| 1304 : | system 'stty','-echo'; | ||
| 1305 : | print "Old passwd: "; | ||
| 1306 : | |||
| 1307 : | $oldpwd = <STDIN>; | ||
| 1308 : | chop $oldpwd; | ||
| 1309 : | |||
| 1310 : | ($name,$coded_pwd,$uid,$gid,$x,$y,$z,$gcos,$home,$shell) | ||
| 1311 : | = getpwnam($ENV{"USER"}); | ||
| 1312 : | |||
| 1313 : | if (crypt($oldpwd,$coded_pwd) ne $coded_pwd) | ||
| 1314 : | { | ||
| 1315 : | print "\nPasswd incorrect\n"; | ||
| 1316 : | exit (1); | ||
| 1317 : | } | ||
| 1318 : | |||
| 1319 : | $oldpwd = ""; # Destroy the evidence! | ||
| 1320 : | |||
| 1321 : | print "\nNew passwd: "; | ||
| 1322 : | |||
| 1323 : | $newpwd = <STDIN>; | ||
| 1324 : | |||
| 1325 : | print "\nRepeat new passwd: "; | ||
| 1326 : | |||
| 1327 : | $rnewpwd = <STDIN>; | ||
| 1328 : | |||
| 1329 : | chop $newpwd; | ||
| 1330 : | chop $rnewpwd; | ||
| 1331 : | |||
| 1332 : | if ($newpwd ne $rnewpwd) | ||
| 1333 : | { | ||
| 1334 : | print "\n Incorrectly typed. Password unchanged.\n"; | ||
| 1335 : | exit (1); | ||
| 1336 : | } | ||
| 1337 : | |||
| 1338 : | $salt = rand(); | ||
| 1339 : | $new_coded_pwd = crypt($newpwd,$salt); | ||
| 1340 : | |||
| 1341 : | print "\n\n$name:$new_coded_pwd:$uid:$gid:$gcos:$home:$shell\n"; | ||
| 1342 : | |||
| 1343 : | |||
| 1344 : | File: unix.info, Node: Fork example, Next: Database example, Prev: Passwd example program, Up: Perl examples | ||
| 1345 : | |||
| 1346 : | Example with `fork()' | ||
| 1347 : | --------------------- | ||
| 1348 : | |||
| 1349 : | The following example uses the `fork' function to start a daemon | ||
| 1350 : | which goes into the background and watches the system to which process | ||
| 1351 : | is using the greatest amount of CPU time each minute. A pipe is opened | ||
| 1352 : | from the BSD `ps' command. | ||
| 1353 : | |||
| 1354 : | #!/local/bin/perl | ||
| 1355 : | # | ||
| 1356 : | # A fork() demo. This program will sit in the background and | ||
| 1357 : | # make a list of the process which uses the maximum CPU average | ||
| 1358 : | # at 1 minute intervals. On a quiet BSD like system this will | ||
| 1359 : | # normally be the swapper (long term scheduler). | ||
| 1360 : | # | ||
| 1361 : | |||
| 1362 : | $true = 1; | ||
| 1363 : | $logfile="perl.cpu.logfile"; | ||
| 1364 : | |||
| 1365 : | print "Max CPU logfile, forking daemon...\n"; | ||
| 1366 : | |||
| 1367 : | if (fork()) | ||
| 1368 : | { | ||
| 1369 : | exit(0); | ||
| 1370 : | } | ||
| 1371 : | |||
| 1372 : | while ($true) | ||
| 1373 : | { | ||
| 1374 : | open (logfile,">> $logfile") || die "Can't open $logfile\n"; | ||
| 1375 : | open (ps,"/bin/ps aux |") || die "Couldn't open a pipe from ps !!\n"; | ||
| 1376 : | |||
| 1377 : | $skip_first_line = <ps>; | ||
| 1378 : | $max_process = <ps>; | ||
| 1379 : | close(ps); | ||
| 1380 : | |||
| 1381 : | print logfile $max_process; | ||
| 1382 : | close(logfile); | ||
| 1383 : | sleep 60; | ||
| 1384 : | |||
| 1385 : | ($a,$b,$c,$d,$e,$f,$g,$size) = stat($logfile); | ||
| 1386 : | |||
| 1387 : | if ($size > 500) | ||
| 1388 : | { | ||
| 1389 : | print STDERR "Log file getting big, better quit!\n"; | ||
| 1390 : | exit(0); | ||
| 1391 : | } | ||
| 1392 : | } | ||
| 1393 : | |||
| 1394 : | |||
| 1395 : | File: unix.info, Node: Database example, Prev: Fork example, Up: Perl examples | ||
| 1396 : | |||
| 1397 : | Example reading databases | ||
| 1398 : | ------------------------- | ||
| 1399 : | |||
| 1400 : | Here is an example program with several of the above features | ||
| 1401 : | demonstrated simultaneously. This following program lists all users who | ||
| 1402 : | have home directories on the current host. If the home area has | ||
| 1403 : | sub-directories, corresponding to groups, then this is specified on the | ||
| 1404 : | command line. The word `home' causes the program to print out the home | ||
| 1405 : | directories of the users. | ||
| 1406 : | |||
| 1407 : | #!/local/bin/perl | ||
| 1408 : | ################################################################## | ||
| 1409 : | # | ||
| 1410 : | # allusers - list all users on named host, i.e. all | ||
| 1411 : | # users who can log into this machine. | ||
| 1412 : | # | ||
| 1413 : | # Syntax: allusers group | ||
| 1414 : | # allusers mygroup home | ||
| 1415 : | # allusers myhost group home | ||
| 1416 : | # | ||
| 1417 : | # NOTE : This command returns only users who are registered on | ||
| 1418 : | # the current host. It will not find users which cannot | ||
| 1419 : | # be validated in the passwd file, or in the named groups | ||
| 1420 : | # in NIS. It assumes that the users belonging to | ||
| 1421 : | # different groups are saved in subdirectories of | ||
| 1422 : | # /home/hostname. | ||
| 1423 : | # | ||
| 1424 : | ################################################################## | ||
| 1425 : | |||
| 1426 : | &arguments(); | ||
| 1427 : | |||
| 1428 : | die "\n" if ( ! -d "/home/$server" ); | ||
| 1429 : | |||
| 1430 : | $disks = `/bin/ls -d /home/$server/$group`; | ||
| 1431 : | |||
| 1432 : | foreach $home (split(/\s/,$disks)) | ||
| 1433 : | { | ||
| 1434 : | open (LS,"cd $home; /bin/ls $home |") || die "allusers: Pipe didn't open"; | ||
| 1435 : | |||
| 1436 : | while (<LS>) | ||
| 1437 : | { | ||
| 1438 : | $exists = ""; | ||
| 1439 : | ($user) = split; | ||
| 1440 : | ($exists,$pw,$uid,$gid,$qu,$cm,$gcos,$dir)=getpwnam($user); | ||
| 1441 : | |||
| 1442 : | if ($exists) | ||
| 1443 : | { | ||
| 1444 : | if ($printhomes) | ||
| 1445 : | { | ||
| 1446 : | print "$dir\n"; | ||
| 1447 : | } | ||
| 1448 : | else | ||
| 1449 : | { | ||
| 1450 : | print "$user\n"; | ||
| 1451 : | } | ||
| 1452 : | } | ||
| 1453 : | } | ||
| 1454 : | close(LS); | ||
| 1455 : | } | ||
| 1456 : | |||
| 1457 : | ######################################################## | ||
| 1458 : | |||
| 1459 : | sub arguments | ||
| 1460 : | { | ||
| 1461 : | $printhomes = 0; | ||
| 1462 : | $group = "*"; | ||
| 1463 : | $server = `/bin/hostname`; | ||
| 1464 : | chop $server; | ||
| 1465 : | |||
| 1466 : | foreach $arg (@ARGV) | ||
| 1467 : | { | ||
| 1468 : | if (substr($arg,0,1) eq "u") | ||
| 1469 : | { | ||
| 1470 : | $group = $arg; | ||
| 1471 : | next; | ||
| 1472 : | } | ||
| 1473 : | |||
| 1474 : | if ($arg eq "home") | ||
| 1475 : | { | ||
| 1476 : | $printhomes = 1; | ||
| 1477 : | next; | ||
| 1478 : | } | ||
| 1479 : | |||
| 1480 : | $server= $arg; #default is to interpret as a server. | ||
| 1481 : | } | ||
| 1482 : | } | ||
| 1483 : | |||
| 1484 : | |||
| 1485 : | File: unix.info, Node: Pattern matching, Next: search and replace, Prev: Perl examples, Up: Perl | ||
| 1486 : | |||
| 1487 : | Pattern matching and extraction | ||
| 1488 : | =============================== | ||
| 1489 : | |||
| 1490 : | Perl has regular expression operators for identifying patterns. The | ||
| 1491 : | operator | ||
| 1492 : | |||
| 1493 : | /REGULAR EXPRESSION/ | ||
| 1494 : | |||
| 1495 : | returns true of false depending on whether the regular expression | ||
| 1496 : | matches the contents of `$_'. For example | ||
| 1497 : | |||
| 1498 : | |||
| 1499 : | if (/perl/) | ||
| 1500 : | { | ||
| 1501 : | print "String contains perl as a substring"; | ||
| 1502 : | } | ||
| 1503 : | |||
| 1504 : | if (/(Sat|Sun)day/) | ||
| 1505 : | { | ||
| 1506 : | print "Weekend day...."; | ||
| 1507 : | } | ||
| 1508 : | The effect is rather like the `grep' command. To use this operator | ||
| 1509 : | on other variables you would write: | ||
| 1510 : | |||
| 1511 : | $variable =~ /REGEXP/ | ||
| 1512 : | Regular expression can contain parenthetic sub-expressions, e.g. | ||
| 1513 : | |||
| 1514 : | if (/(Sat|Sun)day (..)th (.*)/) | ||
| 1515 : | { | ||
| 1516 : | $first = $1; | ||
| 1517 : | $second = $2; | ||
| 1518 : | $third = $3; | ||
| 1519 : | } | ||
| 1520 : | |||
| 1521 : | in which case perl places the objects matched by such sub-expressions | ||
| 1522 : | in the variables `$1', `$2' etc. | ||
| 1523 : |
| Administrator | ViewVC Help |
| Powered by ViewVC 1.0.3 |