Quick Guide to Perl
|
|
You can download the latest Perl package from
http://www.rpmfind.net, while the Windows version is called ActivePerl and is available from
http://www.ActiveState.com/ActivePerl/. Note that you should install Perl 5 or 6 since some of the features described here do not exist in Perl 4.
Web development with Perl
Mason
http://www.masonhq.com/
Bricolage
http://www.bricolage.cc/
Unix-specific system calls
(gname, gpasswd, gid, gmembers) = getgrnam (name);
while (($gname, $gpasswd, $gid, $gmembers) = getgrent) {
# Using group-related infos here
}
setgrent(); # Rewind to first line of /etc/groups
endgrent(); # Move to last line
(gname, gpasswd, gid, gmembers) = getgrid (id);
(name, altnames, addrtype, net) = getnetent(); #Get infos from /etc/networks
(name, altnames, addrtype, addr) = getnetbyaddr (inaddr, inaddrtype);
(name, altnames, addrtype, net) = getnetbyname (inname);
(name, altnames, addrtype, len, addrs) = gethostbyaddr (inaddr, inaddrtype); #Get infos from /etc/hosts
(name, altnames, addrtype, len, addrs) = gethostbyname (inname);
(name, altnames, addrtype, len, addrs) = gethostent();
logname = getlogin();
$pgroup = getpgrp (0);
parentid = getppid();
(username, password, userid, groupid, quota, comment, infofield, homedir, shell) = getpwnam (name);
(username, password, userid, groupid, quota, comment, infofield, homedir, shell) = getpwuid (inputuid);
while (1) {
last unless (($username, $password, $userid) = getpwent());
}
Manipulating strings
$position = index($input, "the");
$position = rindex($string, "the");
$strlen = length($string);
$string = "here is a string";
$_ = "here is a string";
$length = tr/a-zA-Z /a-zA-Z /;
$position = pos($string);
$sub1 = substr ($string, 10, 6);
substr($string, 0, 4) = "This";
$lower = lc("aBcDe"); # $lower is assigned "abcde"
$upper = uc("aBcDe"); # $upper is assigned "ABCDE"
$lower = lcfirst("HELLO"); # $lower is assigned "hELLO"
$upper = ucfirst("hello"); # $upper is assigned "Hello"
$outstr = sprintf("%d = %x hexadecimal or %o octal\n", $num, $num, $num);
chop ($mystring);
chomp($scalar);
$retval = crypt ("sludge", $salt);
@list = ("This", "is", "a", "test");
@foundlist = grep(/^[tT]/, @list);
Converting values
decnum = hex (hexnum);
$intval = int (68.3 / $divisor) + 1;
$num = oct ("177");
$ASCIIval = ord("/");
$slash = chr(47);
Processes
eval ("\$start = tell(MYFILE);");
system ("echo \"hello, world\"");
exec ("vi", "file1");
Note: The exec function is similar to the system function, except that it terminates the current program before starting the new one. exec often is used in conjunction with fork: when fork splits into two processes, the child process starts another program using exec.
pipe (INPUT, OUTPUT);
$retval = fork();
if ($retval != 0) {
# this is the parent process
close (INPUT);
print ("Enter a line of input:\n");
$line = <STDIN>
print OUTPUT ($line);
} else {
# this is the child process
close (OUTPUT);
$line = <INPUT>
print ($line);
exit (0);
}
Note: The pipe function is designed to be used in conjunction with the fork function. It provides a way for the child and parent processes to communicate. The process in which outfile is still open can now send data to the process in which infile is still open. (The child can send data to the parent, or vice versa, depending on which process closes input and which closes output.) If you need to establish two-way communication, you can open two pipes, one in each direction
require ("syscall.ph");
syscall (list);
die ("Cannot open input file");
warn ("Input file is empty");
exit(2);
kill (signal, proclist);
sleep (5);
procid = wait(); #Waits for a child process to terminate
waitpid (procid, waitflag);
Killing a process
- chomp($myname = `echo \$USER`);
- open(PS, "ps -aux | grep myps | grep -v grep |");
-
- while(<PS>) {
- if (/myps/) {
- /^\s*(\w+)\s+(\w+)/;
- chomp($1);
- if ($1 eq $myname) {
- system("kill $2");
- }
- }
- }
-
- close(PS);
Sockets
Setting up a server
$line = "Hello, world!\n";
$port = 2000;
while (getservbyport ($port, "tcp")) { #Check for available port
$port++;
}
($d1, $d2, $prototype) = getprotobyname ("tcp");
($d1, $d2, $d3, $d4, $rawserver) = gethostbyname ('hostname');
$serveraddr = pack ("Sna4x8", 2, $port, $rawserver);
socket (SSOCKET, 2, 1, $prototype);
bind (SSOCKET, $serveraddr);
listen (SSOCKET, 1)
($clientaddr = accept (SOCKET, SSOCKET));
select (SOCKET);
$| = 1;
print SOCKET ("$line\n");
close (SOCKET);
close (SSOCKET);
Setting up a client
$port = 2000;
while (getservbyport ($port, "tcp")) {
$port++;
}
($d1, $d2, $prototype) = getprotobyname ("tcp");
($d1, $d2, $d3, $d4, $rawclient) = gethostbyname ("mercury");
($d1, $d2, $d3, $d4, $rawserver) = gethostbyname ("silver");
$clientaddr = pack ("Sna4x8", 2, 0, $rawclient);
$serveraddr = pack ("Sna4x8", 2, $port, $rawserver);
socket (SOCKET, 2, 1, $prototype) || die ("No socket");
bind (SOCKET, $clientaddr) || die ("Can't bind");
connect (SOCKET, $serveraddr);
$line = <SOCKET>;
print ("$line\n");
close (SOCKET);
Changing direction of data
shutdown (socket, direction);
Note: 0 indicates that the program can send through the socket but can no longer receive data. 1 indicates that the program can receive data from the socket but can no longer send. 2 indicates that both sending and receiving are disallowed.
Control structures
if/elsif/else
if ($number1 == $number2) {
print ("The two numbers are equal.\n");
}
elsif ($number1 == $number2 + 1) {
print ("The first number is greater by one.\n");
}
else {
print ("The two numbers are not equal.\n");
}
while/do/until
while ($number == 5) {
print ("The number is still 5!\n");
}
do {
$line = <STDIN>
} while ($line ne "");
until ($input_answer == $correct_answer) {
print ("Wrong! Keep trying!\n");
$input_answer = <STDIN>;
chop ($input_answer);
}
while (1) {
$line = <STDIN>;
if ($line eq "") {
last;
}
}
for ($count = 1; $count <= $limit; $count++) {
if ($count % 2 == 1) {
next;
}
}
DONE: while ($firstcounter < 10) {
if ($firstcounter == 4) {
last DONE;
}
$firstcounter++;
}
NEXTLINE: $line = <STDIN> ;
if ($line ne "") {
print ($line);
goto NEXTLINE;
}
for
for ($line = <STDIN>, $count = 1; $count <= 3; $line = <STDIN>, $count++) {
print ($line);
}
foreach
foreach $word (@words) {
if ($word eq "the") {
print ("found the word 'the'\n");
}
}
foreach $temp ("This", "is", "a", "list") {
print("$temp ");
}
Subroutines
Pre-defined subroutines BEGIN, END, AUTOLOAD
Perl 5 defines three special subroutines that are executed at specific times. The BEGIN subroutine, which is called when your program starts running. The END subroutine, which is called when your program terminates. The AUTOLOAD subroutine, which is called when your program can't find a subroutine it is supposed to execute:
AUTOLOAD {
print("subroutine $AUTOLOAD not found\n");
print("arguments passed: @_\n");
}
&getnumbers;
sub getnumbers {
$line = <STDIN> ;
$line =~ s/^\s+|\s*\n$//g;
@numbers = split(/\s+/, $line);
}
Note: In Perl 5, you do not need to supply an & character when calling a subroutine if you have already defined the subroutine.
Returning a value
The value of the last expression evaluated by the subroutine is automatically considered to be the subroutine's return value. Another way to ensure that the return value from a subroutine is the value you want is to use the return statement. The syntax for the return statement is return (retval);
Local variables
In Perl 5, there are two statements used to define local variables: The my statement, which defines variables that exist only inside a subroutine. The local statement, which defines variables that do not exist inside the main program, but inside the subroutine and any subroutines called by the subroutine. In Perl 4, the my statement is not defined, so you must
use local to define a variable that is not known to the main program:
sub get_total {
my ($total, $inputline, @subwords);
my ($index, $retval);
Passing parameters
By value
- &printnum ($number1, $number2, $number3);
-
- sub printnum {
- my($number1, $number2, $number3) = @_;
- my($total);
- print ("The numbers you entered: ");
- print ("$number1 $number2 $number3\n");
- $total = $number1 + $number2 + $number3;
- print ("The total: $total\n");
- }
-
- sub printnum2 {
- my($total);
- $total = $_[0] + $_[1] + $_[2];
- print ("The total: $total\n");
- }
By reference
- &my_sub(*myarray);
-
- sub my_sub
- {
- my (*subarray) = @_;
- $arraylength = @subarray;
- }
Building packages
Package
- package mypack;
-
- sub Test1
- {
- print "hello";
- }
-
- return 1;
Application
- use mypack;
-
- mypack->Test1;
Operators
Comparison operators
String operator |
Numeric operator |
lt |
< |
gt |
> |
eq |
== |
le |
<= |
ge |
>= |
ne |
!= |
cmp |
<=> |
Boolean operators
||/or
if ($a || $b)
if ($a or $b)
&&/and
if ($a && $b)
if ($a and $b)
!/not
if (! $a)
if (not $a)
xor
if ($a xor $b)
Ternary operator
$result = $var == 0 ? 14 : 7;
String operators
Concatenation
$newstring = "potato" . "head"
Pattern repetition
copystring = "t";
$repeats = 5;
$newstring = $copystring x $repeats;
Simplified assignment operators
$a = 1;
| none (basic assignment) |
$a -= 1;
| $a = $a - 1;
|
$a *= 2;
| $a = $a * 2;
|
$a /= 2;
| $a = $a / 2;
|
$a %= 2;
| $a = $a % 2;
|
$a **= 2;
| $a = $a ** 2;
|
$a &= 2;
| $a = $a & 2;
|
$a |= 2;
| $a = $a | 2;
|
$a ^= 2; |
$a = $a ^ 2; |
$a++; |
$a = $a + 1; |
++$a; |
$a = $a + 1; |
$a--; |
$a = $a - 1; |
--$a; |
$a = $a - 1; |
Plain arrays and associative arrays
Plain arrays
Filling an array manually
@array = (1, 2, 3);
@array = <STDIN> ;
Here is my first line of data.
Here is another line.
Here is the last line.
^D
Filling an array automatically
@day_of_month = ("01".."31");
Extracting a value
$scalar = $array[0];
Defining/undefining values
if (defined ($array[$i])) {
print ("element ", $i+1, " is defined\n");
}
undef ($myvar);
Copying a whole array
@result = @original;
Copying a partial array
@subarray = @array[0,1];
@array[0,1] = ("string", 46);
@array[1,2] = @array[2,1];
Displaying contents
print (@subarray, "\n");
twothreefour
print ("@array\n");
bar baz dip foo
Command-line parameters
You can access individual elements of @ARGV, eg.
$var = $ARGV[0];
To determine the number of command-line arguments, assign the array variable to a scalar variable, eg. $numargs = @ARGV;
Sorting et al.
@array2 = sort (@array);
@array2 = reverse(@array);
$string = join(" ", "this", "is", "a", "string");
$string = "words::separated::by::colons";
@array = split(/::/, $string);
Modifying elements
@array = ("1", "2", "3", "4");
splice (@array, 1, 2, ("two", "three"));
=> Now, @array is ("1", "two", "three", "4")
unshift (@array, "newitem");
push (@array, "newitem");
$popped = pop (@array);
@deleted = splice (@array, 8, 2);
@mylist = ("1", "2", "3");
$firstval = shift(@mylist);
=> @mylist is now ("2", "3")
Associative arrays, a.k.a. hash arrays
$fruit{"bananas"} = 1;
%fruit = ("apples", 17, "bananas", 9, "oranges", "none");
%fruit = ("apples" => 17, "bananas" => 9, "oranges" => "none");
@fruit = ("apples", 6, "cherries", 8, "oranges", 11);
%fruit = @fruit;
delete($fruit{"orange"});
@fruitsubs = keys(%fruits);
@fruitvalues = values(%fruits);
Extracting values
foreach $capword (sort keys(%wordlist)) {
print ("$capword: $wordlist{$capword}\n");
}
%records = ("Maris", 61, "Aaron", 755, "Young", 511);
while (($holder, $record) = each(%records)) {
# stuff goes here
}
Modifying elements
Input/output
Interactive input
$inputline = <STDIN> ;
chomp($inputline);
print ($inputline, $inputline);
Opening files
Read-only mode (default)
open(FILE1, "/u/jqpublic/file1");
Write mode
open (OUTFILE, ">/u/jqpublic/outfile");
Append mode
open (APPENDFILE, ">>/u/jqpublic/appendfile");
Read/write mode
open (READWRITE, "+<file1");
open (READWRITE, "+>file1");
Subroutine to open a file
- sub OpenFile
- {
-
- my($handle,$file) =
@_;
- open($handle, $file)
|| die ("Err: Cannot open file $file\n");
- }
Reading from files
if (open(MYFILE, "file1")) {
$line = <MYFILE> ;
while ($line ne "") {
print ($line);
$line = <MYFILE> ;
}
}
if (open(MYFILE, "file1")) {
@array = <MYFILE> ;
} else {
die ("cannot open input file file1\n");
}
Reading some bytes into a buffer
read (MYFILE, $mybuffer, 80);
read (MYFILE, $mybuffer, 40, 80); #Skip the first 80 bytes already stored in $mybuffer, and read 40 bytes from MYFILE
singlechar = getc(INFILE);
Checking for end-of-file status
while ($line = <>) {
print ($line);
if (eof) {
print ("-- end of current file --\n");
}
}
Note: When using eof, this affects each file that is passed as argument. When using eof(), this works only once all files are read! This distinction is only meaningful when you are using the <> operator. If you are just reading from a single file, it doesn't matter whether you supply parentheses or not:
while ($line = <STDIN>) {
if (eof) { # you can also use eof() here
}
}
Moving forward and backward
$currentposition = tell(TEMPFILE);
seek (TEMPFILE, 10, 0); #Jump to byte 10 from beginning of file
seek(MYFILE, -80, 1); #Jump back 80 bytes from current position
Note: In the seek function, the second variable indicates the number of bytes to skip. The third variable is 0 (starting from the beginning of the file), 1 (starting with the current position), or 2 (starting from the end of the file.)
Writing to files
open(OUTFILE, ">outfile");
print OUTFILE ($line);
Writing to STDOUT/STDERR
print ("Here is a line of output.\n");
print STDOUT ("Here is a line of output.\n");
print STDERR ("File file1 opened successfully.\n");
open (STDOUT, ">file1");
open (STDERR, ">&STDOUT"); #redirect STDERR to STDOUT
print STDOUT ("line 1\n");
print STDERR ("line 2\n"); #Note: STDERR buffer is flushed _before_ STDOUT!
close (STDOUT);
close (STDERR);
Note: To disable buffering, use $| = 1 (STDOUT by default) and select(STDERR) ; $| = 1 (for file handles other than STDOUT).
Reading a configuration file
- sub ReadINI
- {
- my($file) = @_;
-
- OpenFile(MYINI,$file);
-
- while (<MYINI>)
{
- if
(! /^ *#/) {
- /^
*(.+) *= *(.+)/;
- $ini{$1}=$2;
- }
- }
- close MYINI;
-
- foreach(sort keys %ini)
{
- if
($ini{$_} eq "") {
- print
"Err: Parameter $_ in file $file is empty.\n";
- return
FALSE;
- }
- }
-
- if (scalar(keys(%ini))
ne 2) {
- print
"Err: Expected 2 items in $file, but found scalar(keys(%ini))\n";
- return
FALSE;
- }
-
- $input = $ini{"input_file"};
- $output = $ini{"output_file"};
-
- return TRUE;
- }
Using pipes
open (CAT, "cat file*|");
$input = <CAT> ;
File operators
The following operators can be used to test various conditions regarding files, eg. does a file exist, is it in read-only mode, etc. For instance, the following snipet checks whether "/u/jqpublic/file1" exists, without having to use an
open
statement:
if (-e "/u/jqpublic/file1") {
print ("The file exists.\n");
}
Operator | Description
|
-b | Is name a block device?
|
-c | Is name a character device?
|
-d | Is name a directory?
|
-e | Does name exist?
|
-f | Is name an ordinary file?
|
-g | Does name have its setgid bit set?
|
-k | Does name have its "sticky bit" set?
|
-l | Is name a symbolic link?
|
-o | Is name owned by the user?
|
-p | Is name a named pipe?
|
-r | Is name a readable file?
|
-s | Is name a non-empty file?
|
-t | Does name represent a terminal?
|
-u | Does name have its setuid bit set?
|
-w | Is name a writable file?
|
-x | Is name an executable file?
|
-z | Is name an empty file?
|
-A | How long since name accessed?
|
-B | Is name a binary file?
|
-C | How long since name's inode accessed?
|
-M | How long since name modified?
|
-O | Is name owned by the "real user" only?*
|
-R | Is name readable by the "real user" only?*
|
-S | Is name a socket?
|
-T | Is name a text file?
|
-W | Is name writable by the "real user" only?*
|
-X | Is name executable by the "real user" only?*
|
* In this case, the "real user" is the userid specified at login, as opposed to the effective user ID, which is the userid under which you currently are working. (On some systems, a
command such as /user/local/etc/suid enables you to change your effective user ID.)
|
Other file operations
Renaming files
rename ("/u/jqpublic/name1", "/u/janedoe/name2");
Managing links
symlink("/u/jqpublic/file", "/u/janedoe/newfile");
link ("/u/jqpublic/file", "/u/janedoe/newfile");
unlink ("/u/jqpublic/file"); #If more links exist, they are not removed
$linkname = readlink("/u/janedoe/newfile");
Changing file access
chmod (permissions, filelist);
chown (userid, groupid, filelist);
$oldperms = umask(0022);
Pipes
open (MESSAGE, "| mail dave");
print MESSAGE ("Hi, Dave! Your Perl program sent this!\n");
close (MESSAGE);
Getting the size of a file
$size = -s "outfile"
Checking for end-of-file
if (eof) {
#Do sthing
}
Working with directories
mkdir ("/u/jqpublic/newdir", 0777);
chdir ("/u/jqpublic/newdir");
rmdir (dirname);
opendir(HOMEDIR, "/u/jqpublic");
while ($filename = readdir(HOMEDIR)) {
print ("$filename\n");
}
closedir(HOMEDIR);
opendir(HOMEDIR, "/u/jqpublic");
@files = readdir(HOMEDIR);
closedir(HOMEDIR);
foreach $file (sort @files) {
print ("$file\n");
}
$location = telldir (mydir);
seekdir(mydir, location);
rewinddir (mydir);
Pattern matching
From So What's A $#!%% Regular Expression, Anyway?!
Escape sequence |
Description | Range
|
\d | Any digit
| [0-9] |
\D | Anything other than a digit
| [^0-9] |
\w | Any word character
| [_0-9a-zA-Z] |
\W | Anything not a word character
| [^_0-9a-zA-Z] |
\s | White space
| [ \r\t\n\f] |
\S | Anything other than white space
| [^ \r\t\n\f] |
Option | Description
|
g | Match all possible patterns
|
i | Ignore case
|
m | Treat string as multiple lines
|
o | Only evaluate once
|
s | Treat string as single line
|
x | Ignore white space in pattern
|
Check for a pattern
if ($var =~ /abc/) {
#Pattern found
}
Checking for the occurence of a character
?
The ? character matches zero or one occurrence of the preceding character. For example, the pattern /de?f/
*
Zero or more
The . character is often used in conjunction with the * character. For example, the following pattern matches
any string that contains the character d preceding the character f:
/d.*f/
+
One or more
Specific number of occurences
For example, the pattern /de{1,3}f/ matches d, followed by one, two, or three occurrences
of e, followed by f. This means that def,deef, and deeef match, but df and deeeef do not.
Checking for alpha-numeric patterns
/[0-9a-zA-Z]/
Beginning/end of a line
^...$
Word boundaries
/\bdef\b/
The \B pattern anchor is the opposite of \b. \B matches only if the pattern is contained in a word. For example, the pattern
/\Bdef/
matches abcdef, but not def. Similarly, the pattern
/def\B/
matches defghi, and
/\Bdef\B/
matches cdefg or abcdefghi, but not def, defghi, or abcdef
Excluding a pattern
When the ^ character appears as the first character after the [, it indicates that the pattern is to match any character except the ones displayed between the [ and ].
/d[^eE]f/
Alternative patterns
The special character | enables you to specify two or
more alternatives to choose from when matching a pattern. For
example, the pattern
/def|ghi/ matches either def or ghi.
Refer to a previous pattern
/\d{2}([\W])\d{2}
\1\d{2}/ This matches two digits, a non-word character, two more digits,
the same non-word character, and two more digits.
Note that pattern-sequence memory is preserved only for the length of the pattern. To get around this problem, Perl defines special built-in variables
that remember the value of patterns matched in parentheses. These
special variables are named $n, where n is the
nth set of parentheses in the pattern.
For example, consider the following:
$string = "This string contains the number 25.11." $string =~ /-?(\d+)\.?(\d+)/; $integerpart = $1; $decimalpart = $2;
There is also one other built-in scalar variable, $&,
which contains the entire matched pattern, as follows:
$string = "This string contains the number 25.11." $string =~ /-?(\d+)\.?(\d+)/; $number = $& Here, the pattern matched is 25.11, which is stored in
$& and then assigned to $number.
Changing the default / pattern delimiter
To make it easier to write patterns that include / characters,
Perl enables you to use any pattern-delimiter character you like.
The following pattern also matches the directory /u/jqpublic/perl/prog1:
m!/u/jqpublic/perl/prog1! Here, the m indicates the pattern-matching operation.
If you are using a pattern delimiter other than /, you
must include the m.
Finding where a pattern occurs
If you need to know how much of a string has been searched by the pattern matcher when the g operator is specified, use the pos function. $offset = pos($string); This returns the position at which the next pattern match will be started.
You can reposition the pattern matcher by putting pos()
on the left side of an assignment.
pos($string) = $newoffset; This tells the Perl interpreter to start the next pattern match
at the position specified by $newoffset.
Ignoring end-of-line characters
The m option tells the Perl interpreter that the string
to be matched contains multiple lines of text. When the m
option is specified, the ^ special character matches either the start of the string or the start of any new line. For example, the pattern /^The/m matches the word The in This pattern matches\nThe first word on the second line
Restrict search to the first occurence
The o option enables you to tell the Perl interpreter that a pattern is to be evaluated only once. For example, consider the following:
$var = 1;
$line = <STDIN>;
while ($var < 10) {
$result = $line =~ /$var/o;
$line = <STDIN>;
$var++;
}
The s option specifies that the string to be matched is to be treated as a single line of text. In this case, the . special character matches every character in a string, including the newline character. For example, the pattern
/a.*bc/s
is matched successfully in the following string:
axxxxx \nxxxxbc
If the s option is not specified, this pattern does not
match, because the . character does not match the newline.
Perl 5 makes life a little easier by supplying the x
option. This tells the Perl interpreter to ignore white space
in a pattern unless it is preceded by a backslash. This means
that the preceding pattern can be rewritten as the following,
which is much easier to follow:
/\d{2} ([\W]) \d{2} \1 \d{2}/x Here is an example of a pattern containing an actual blank space:
/[A-Z] [a-z]+ \ [A-Z] [a-z]+ /x This matches a name in the standard first-name/last-name format
(such as John Smith). Normally, you won't want to use
the x option if you're actually trying to match white
space, because you wind up with the backslash problem all over
again.
$string = "abc123def";
$string =~ s/123/456/;
The g option changes all occurrences of a pattern in a particular string. For example, the following substitution puts parentheses around any number in the string:
s/(\d+)/($1)/g
The e option treats the replacement string as an expression,
which it evaluates before replacing. For example, consider the following:
$string = "0abc1";
$string =~ s/[a-zA-Z]+/$& x 2/e;
The substitution shown here is a quick way to duplicate part of
a string. Here's how it works:
The pattern /[a-zA-Z]+/ matches abc, which
is stored in the built-in variable $&.
The e option indicates that the replacement string,
$& x 2, is to be treated as an expression. This expression
is evaluated, producing the result abcabc.
abcabc is substituted for abc in the string
stored in $string. This means that the new value of $string is 0abcabc1.
Converting patterns
$string = "abcdefghicba";
$string =~ tr/abc/def/;
Option | Description
|
c | Translate all characters not specified
|
d | Delete all specified characters
|
s | Replace multiple identical output characters with a single character
|
The c option (c is for "complement")
translates all characters that are not specified. For example,
the statement
$string =~ tr/\d/ /c; replaces everything that is not a digit with a space.
The d option deletes every specified character.
$string =~ tr/\t //d; This deletes all the tabs and spaces from $string.
The s option (for "squeeze") checks the output
from the translation. If two or more consecutive characters translate
to the same output character, only one output character is actually
used. For example, the following replaces everything that is not
a digit and outputs only one space between digits:
$string =~ tr/0-9/ /cs;
Formatting output
printf
printf("The number I want to print is %d.\n", $number);
Specifier | Description
|
%c | Single character
|
%d | Integer in decimal (base-10) format
|
%e | Floating-point number in scientific notation
|
%f | Floating-point number in "normal" (fixed-point) notation
|
%g | Floating-point number in compact format
|
%o | Integer in octal (base-8) format
|
%s | Character string
|
%u | Unsigned integer
|
%x | Integer in hexadecimal (base-16) format
|
format
- sub DisplayHeader
- {
- # Two items expected as input
- $~ = "MYHEADER";
-
- write;
-
- format MYHEADER =
- ===============================================================================
- @<<<<<<<<<<@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
- $empty,@_
- ===============================================================================
- .
-
- }
-
- Important: Just like HERE documents (<<), the part between
"format" and "." must be on the first column
-
$^ = "TOP_OF_PAGE"
$= = 60;
$~ = "MYFORMAT"
write;
format TOP_OF_PAGE =
Page @<<.
$%
.
format MYFORMAT =
==========================================================
The winning number is @<<<<<<!
$winnum
==========================================================
.
Field | Value-field format |
@<<< | Left-justified output |
@>>> | Right-justified output |
@||| | Centered output |
@##.## | Fixed-precision numeric |
@* | Multiline text |
The output can be sent to a file through either write (MYFILE) or the select (MYFILE) command. Note that the latter also affects the print command:
write (MYFILE);
select(MYFILE);
$~ = "MYFORMAT"
write;
select(STDOUT);
$oldfile = select(NEWFILE);
$~ = "MYFORMAT"
write;
select($oldfile);
System variables
- Global Scalar Variables
- The Default Scalar Variable: $_
- The Program Name: $0
- The User ID: $< and $>
-
The Group ID: $(
and $)
-
The Version Number: $]
-
The Input Line Separator: $/
-
The Output Line Separator: $
-
The Output Field Separator: $,
-
The Array Element Separator: $"
-
The Number Output Format: $#
-
The eval Error Message:
$@
-
The System Error Code: $?
-
The System Error Message: $!
-
The Current Line Number: $.
-
Multiline Matching: $*
-
The First Array Subscript: $[
-
Multidimensional Associative Arrays and the $;
Variable
-
The Word-Break Specifier: $:
-
The Perl Process ID: $$
-
The Current Filename: $ARGV
-
The Write Accumulator: $^A
-
The Internal Debugging Value: $^D
-
The System File Flag: $^F
-
Controlling File Editing Using $^I
-
The Format Form-Feed Character: $^L
-
Controlling Debugging: $^P
-
The Program Start Time: $^T
-
Suppressing Warning Messages: $^W
-
The $^X Variable
-
Pattern System Variables
-
Retrieving Matched Subpatterns
-
Retrieving the Entire Pattern: $&
-
Retrieving the Unmatched Text: the $`
and $' Variables
-
The $+ Variable
-
File System Variables
-
The Default Print Format: $~
-
Specifying Page Length: $=
-
Lines Remaining on the Page: $-
-
The Page Header Print Format: $^
-
Buffering Output: $|
-
The Current Page Number: $%
-
Array System Variables
-
The @_ Variable
-
The @ARGV Variable
-
The @F Variable
-
The @INC Variable
-
The %INC Variable
-
The %ENV Variable
-
The %SIG Variable
-
Built-In File Variables
-
STDIN, STDOUT,
and STDERR
-
ARGV
-
DATA
-
The Underscore File Variable
GUI
Resources