Perl: Example
Same situation as in the awk example, but additionaly a mail message is
generated for each user.
open(COM, ">AUTH.COM");
print COM "\$mcr authorize\n";
$group = 100;
$uid = 7;
open(LIST, "TEMPAWK.TXT");
while (<LIST>) {
s/\//_/g;
@words = split();
if ($words[0] =~ /[1-9]/){
print COM "copy default ", $words[1], "-\n";
print COM " /owner=\"", $words[1], ",", $words[2], "\"-\n" ;
print COM " /device=", $words[3], "\$root: -\n";
printf COM " /directory=[%s]/uic=[%o,%o]-\n", $words[1], $group, $uid;
print COM " /password=x", $words[4], "x\n";
$uid++;
$tmpnam = ">" . $words[1] . ".txt";
open(MAIL, $tmpnam);
print MAIL "Dear Mr. ", $words[1], "!\n" ;
print MAIL "Your account has been setup.\n";
print MAIL "Initital Password is x",$words[4], "x.\n";
print MAIL "Greetings, System\n";
close(MAIL);
}
}
print COM "exit\n";
close(COM);
close(LIST);
Explanation
- Variables
- Variable names start in Perl with a $sign,
Arrays with a @.
Elemets of the array @array are referenced as
$array[index].
- File Input/Output
- Files have to be opened and closed explicitly
- open(FILEHANDLE, FILE)
- Open the file given in FILE and associate it with the symbolic
name FILEHANDLE, which is used further on in the program.
FILE opens an existing file for reading,
>FILE generates a new file for writing.
- close(FILEHANDLE)
- Closes the file associated with FILEHANDLE.
- Output
-
- print FILEHANDLE LIST
- Write to the file associated with FILEHANDLE the elements given
in LIST (e.g. Character string "Hello World!\n", Variables $uid).
- printf FILEHANDLE FORMAT, LIST
- Similar to print, but FORMAT may contain additional formating
instructions (e.g. %o, print number using the octal representation).
- while (<FILEHANDLE>)
- Special form of the while statement. The condition is true, as long
as Lines can be read from the FILEHANDLE.
- s/\//_/g
- One possibility to edit strings is to use typical sed
syntax. The given line substitutes (substitute)
all (global) / with _.
Since / is used to separate patterns in sed it has to be escaped with a \.
- split()
- The split function splits ;-) a character string into an array of
strings (this happens automagically in awk when a line is read!). Split
takes three optional parameters
split(/pattern/,expression,limit)
- /pattern/ is a regular expression, which tells perl where to cut
the string.
Default: Arbitrary number of whitespace (d.h. /[ \t\n]+/),
including Tab and newline.
- expression is the character string, which should be split.
Default: $_ is the current input area. Normally this is the
last line read in.
- limit tells perl how many substrings to create.
Default: As many as possible for a given input string.
Martin P.J. Zinser