(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());
}
$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);
decnum = hex (hexnum);
$intval = int (68.3 / $divisor) + 1;
$num = oct ("177");
$ASCIIval = ord("/");
$slash = chr(47);
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);
$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);
$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);
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.
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 ($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 ($line = <STDIN>, $count = 1; $count <= 3; $line = <STDIN>, $count++) {
print ($line);
}
foreach $word (@words) {
if ($word eq "the") {
print ("found the word 'the'\n");
}
}
foreach $temp ("This", "is", "a", "list") {
print("$temp ");
}
&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.
sub get_total {
my ($total, $inputline, @subwords);
my ($index, $retval);
if ($a || $b) if ($a or $b)
if ($a && $b) if ($a and $b)
if (! $a) if (not $a)
if ($a xor $b)
$result = $var == 0 ? 14 : 7;
$newstring = "potato" . "head"
copystring = "t"; $repeats = 5; $newstring = $copystring x $repeats;
@array = (1, 2, 3); @array = <STDIN> ; Here is my first line of data. Here is another line. Here is the last line. ^D
@day_of_month = ("01".."31");
$scalar = $array[0];
if (defined ($array[$i])) {
print ("element ", $i+1, " is defined\n");
}
undef ($myvar);
@result = @original;
@subarray = @array[0,1];
@array[0,1] = ("string", 46);
@array[1,2] = @array[2,1];
print (@subarray, "\n");
twothreefour
print ("@array\n");
bar baz dip foo
$var = $ARGV[0];To determine the number of command-line arguments, assign the array variable to a scalar variable, eg. $numargs = @ARGV;
@array2 = sort (@array);
@array2 = reverse(@array);
$string = join(" ", "this", "is", "a", "string");
$string = "words::separated::by::colons";
@array = split(/::/, $string);
@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")
$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);
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
}
$inputline = <STDIN> ; chomp($inputline); print ($inputline, $inputline);
open(FILE1, "/u/jqpublic/file1");
open (OUTFILE, ">/u/jqpublic/outfile");
open (APPENDFILE, ">>/u/jqpublic/appendfile");
open (READWRITE, "+<file1"); open (READWRITE, "+>file1");
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");
}
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);
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
}
}
$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 positionNote: 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.)
open(OUTFILE, ">outfile"); print OUTFILE ($line);
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).
open (CAT, "cat file*|"); $input = <CAT> ;
open statement:
if (-e "/u/jqpublic/file1") {
print ("The file exists.\n");
}
rename ("/u/jqpublic/name1", "/u/janedoe/name2");
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");
chmod (permissions, filelist); chown (userid, groupid, filelist); $oldperms = umask(0022);
open (MESSAGE, "| mail dave");
print MESSAGE ("Hi, Dave! Your Perl program sent this!\n");
close (MESSAGE);
$size = -s "outfile"
if (eof) {
#Do sthing
}
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);
if ($var =~ /abc/) {
#Pattern found
}
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.
$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.
printf("The number I want to print is %d.\n", $number);
$^ = "TOP_OF_PAGE" $= = 60; $~ = "MYFORMAT" write; format TOP_OF_PAGE = Page @<<. $% . format MYFORMAT = ========================================================== The winning number is @<<<<<<! $winnum ========================================================== .
write (MYFILE); select(MYFILE); $~ = "MYFORMAT" write; select(STDOUT); $oldfile = select(NEWFILE); $~ = "MYFORMAT" write; select($oldfile);