Perl Tutorials

The 12th chapter in Perl5 quotation/indicator

First, quotation synopsis

The quotation is an indicator, may aim at the variable, the array, the Hasche table (also to be called connection array) even the subroutine. Pascal or the C programmer should to quotes (i.e. indicator) the concept be very familiar, the quotation is some value address, is decided to its use by the programmer and the language stipulation. In Perl, may be called the quotation the indicator, the two are general, non-difference. The quotation is very useful in the foundation complex data aspect.

In Perl5 two kind of quotation type for hard quotation and mark quotation. The mark quotation includes the variable name, it to movement when founds the variable name and locates is very useful, basically, the mark quotation looks like the filename or in the UNIX system’s soft link. But quotes hardly looks like in filing system’s hard link.

The Perl4 only admissible mark quotation, causes some difficulties to the use. For example, only allows through the name (named _main{}) to establish the index to the package of symbolic name Hasche table. Perl5 permits the data the hard quotation, facilitated are many.

Hard quotation track quotation counting, when its number is the zero hour, Perl automatic the project release which will quote, if this project will be an object, will then analyze the construction to release in the memory pond. Perl is in itself an object-oriented language, because in Perl anything is an object, package and the module causes the object change in the use.

Simple variable’s hard quotation is very simple, regarding the non-simple variable’s quotation, how you can explicit relieve quotes and tells its should do, for details sees “In the Chapter of Perl Object-oriented Programming”.

Second, use quotation

In this chapter, the simple variable refers to looks like $pointer such variable, $pointer only contains a data item, its may for the digit, the string of character or the address.

Any simple variable may preserve the hard quotation. Because the array and the Hasche table include many simple variables, therefore may establish the complex construction of data which many kinds of combinations become, like array array, Hasche table array, subroutine Hasche table and so on. So long as you understood that actually is only in uses the simple variable in the work, should be possible correct to relieve the quotation correctly in the most complex structure.

First looks at some essential points.

If the $pointer value is an array indicator, visits in the array through form @$pointer the element. The form @$pointer significance is “takes out in $pointer the address to be worthwhile makes the array use”. Similar, %$pointer is aims in the Hasche table the first element quotation.

Has many kinds of construction quotation method, may nearly to any data establishment quotation, like the array, the simple variable, the subroutine, the document handle, as well as–The C programmer will be interested–Quotation. Perl enables you to have ability to write oneself does the muddled extremely complex code.:)

Below has a look in Perl the foundation and the use quotation method.

Third, use backlash () instruction character

In the backlash instruction character and the C language transmits the address the instruction character & function to be similar. Generally is with foundation variable another new quotation. Below for foundation simple variable quotation example:

$variavle = 22;
$pointer = $variable;
$ice = “jello”;
$iceprt = $ice;

Quotes the $pointer direction to have the $variable value position, quotes the $iceptr direction ” jello “. Even if initial quotation $variable has destroyed, still might visit this value through $pointer, this is a hard quotation, must therefore simultaneously destroy $pointer and $variable so that this space releases in the memory pond.
In the example above, what quotation variable $pointer saves is the $variable address, but is not the value itself, must obtain the value, the form is two $ mark, as follows:

#! /usr/bin/perl
$value = 10;
$pointer = $value;
printf “n Pointer Address $pointer of $value n”;
printf “n What Pointer * ($pointer) points to $$pointern”;

The result output is as follows:

Pointer Address SCALAR(0x806c520) of 10
What Pointer * (SCALAR(0x806cᓈ)) points to 10

Each time the movement, will output in the result the address to change, but may see $pointer will give the address, but $$pointer will give $variable the value.
Looked that the address the demonstration, the SCALAR following string hexadecimal system, SCALAR explained this address direction simple variable (i.e. scalar), the following digit is the actual storage value address.

Attention: The indicator is an address, may visit this address place storage through the indicator the data. If the indicator has pointed at the invalid address, will obtain not the correct data. Usually in the situation, Perl will return to the NULL value, but should not rely on this, certainly must in the procedure all indicator initialization, aim correctly the effective data item.

Fourth, quotation and array

About the Perl language should remember a most important spot possibly is: In the Perl array and the Hasche table are throughout univariate. Therefore, the array and the Hasche table only preserve the scalar value, stores the array or other complex data structure not directly. The array member or is the number (or string of character) either is quotes.
May look like to the array and the Hasche table to the simple variable same use backlash instruction character, the array quotation are as follows:

1 #! /usr/bin/perl
2 #
3 # Using Array references
4 #
5 $pointer = @ARGV;
6 printf “n Pointer Address of ARGV = $pointern”;
7 $i = scalar(@$pointer);
8 printf “n Number of arguments: $i n”;
9 $i = 0;
10 foreach (@$pointer) {
11 printf “$i: $$pointer[$i++]; n”;
12}

The movement result is as follows:

$ test 1 2 3 4
Pointer Address of ARGV = ARRAY(0x806c378)
Number of arguments: 4
0: 1;
1: 2;
2: 3;
3: 4;

5th about to quotes $pointer directional array @ARGV, the 6th line outputs ARGV the address. the $pointer returns array first element’s address, this and in the C language’s array indicator is similar. 7th line of transfer function scalar() obtains the array the element integer, this parameter may also be @ARGV, but must use @$pointer with the indicator the form to assign its type is an array, $pointer gives the address, the @ nomenclature transmission address for the array first element address. The 10th line with 7th line of similar, the 11th line $$pointer[$i] lists all elements with the form.
To is connected the array use backlash instruction character the method is the same–Changes into all incidence numbers set name quotes $poniter. Attention array and simple variable (scalar) when quotation demonstration has the type–ARRAY and SCALAR, the Hasche table (connection array) and the function is also same, respectively is HASH and CODE. Below is the Hasche table quotation example.

#! /usr/bin/perl
1 #
2 # Using Associative Array references
3 #
4 %month = (
5 ’01′, ‘Jan’,
6 ’02′, ‘Feb’,
7 ’03′, ‘Mar’,
8 ’04′, ‘Apr’,
9 ’05′, ‘May’,
10 ’06′, ‘Jun’,
11 ’07′, ‘Jul’,
12 ’08′, ‘Aug’,
13 ’09′, ‘Sep’,
14 ’10′, ‘Oct’,
15 ’11′, ‘Nov’,
16 ’12′, ‘Dec’,
17);
18
19 $pointer = %month;
20
21 printf “n Address of hash = $pointern”;
22
23 #
24 # The following lines would be used to print out the
25 # contents of the associative array if %month was used.
26 #
27 # foreach $i (sort keys %month) {
28 # printf “n $i $$pointer{$i}”;
29 #}
30
31 #
32 # The reference to the associative array via $pointer
33 #
34 foreach $i (sort
keys %$pointer) {
35 printf “$i is $$pointer{$i} n”;
36}

The result output is as follows:

$ mth
Address of hash = HASH(0x806c52c)
01 is Jan
02 is Feb
03 is Mar
04 is Apr
05 is May
06 is Jun
07 is Jul
08 is Aug
09 is Sep
10 is Oct
11 is Nov
12 is Dec

Is similar with the array, through the quotation visit Hasche table’s element form for $$pointer{$index}, certainly, $index is the Hasche table key value, but is not only a digit. Also several kind of visit form, in addition, the construction Hasche table may also use the => instruction character, the readability many. Below looks at an example again:

1 #! /usr/bin/perl
2 #
3 # Using Array references
4 #
5 %weekday = (
6 ’01′ => ‘Mon’,
7 ’02′ => ‘Tue’,
8 ’03′ => ‘Wed’,
9 ’04′ => ‘Thu’,
10 ’05′ => ‘Fri’,
11 ’06′ => ‘Sat’,
12 ’07′ => ‘Sun’,
13 );
14 $pointer = %weekday;
15 $i = ’05′;
16 printf “n ================== start test ================= n”;
17 #
18 # These next two lines should show an output
19 #
20 printf ‘$$pointer{$i} is’;
21 printf “$$pointer{$i} n”;
22 printf ‘$ {$pointer} {$i} is’;
23 printf “$ {$pointer} {$i} n”;
24 printf ‘$pointer->{$i} is’;
25
26 printf “$pointer->{$i}n”;
27 #
28 # These next two lines should not show anything 29 #
30 printf ‘$ {$pointer{$i}} is’;
31 printf “$ {$pointer{$i}} n”;
32 printf ‘$ {$pointer->{$i}} is’;
33 printf “$ {$pointer->{$i}}”;
34 printf “n ================== end of test ================= n”;
35

The result output is as follows:

================== start test =================
$$pointer{$i} is Fri
$ {$pointer} {$i} is Fri
$pointer->{$i} is Fri
$ {$pointer{$i}} is
$ {$pointer->{$i}} is
================== end of test =================

May see that the first three form’s output had demonstrated the anticipated result, then two kinds do not have. When you are not clear to be whether correct time, the output result has a look. In Perl, has not the explicit code to use the print sentence to lose tests, how can this cause your clear Perl is explains your code.

Fifth, multi-dimensional array

Sentence @array = list; May found the array the quotation, the parenthesis may found the anonymous array the quotation. The following sentence to use in the three-dimensional array example which draws:

$line = ['solid', 'black', ['1', '2', '3'], ['4', '5', '6']];

This sentence established one including four element three-dimensional arrays, variable $line has aimed at this array. The first two elements are the scalar, the storage line type and the color, the latter two elements are the anonymous array quotation, the storage line beginning and the end point. Visits its element grammar to be as follows:

$arrayReference->[$index] single-dimensional array
$arrayReference->[$index1][$index2] two-dimensional array
$arrayReference->[$index1][$index2][$index3] three-dimensional array

May found in yours intelligence, the design experience and in computer’s memory permission situation to the utmost the complex structure, but should better to possibly read or manages your code person friendly somewhat–Causes code simple as far as possible. On the other hand, if you want to show off your programming ability to others, Perl the enough opportunity and ability compilation link the unavoidable muddled code for you.:)
Suggested: When you want to use is more than the three dimensional array, the best consideration uses other construction of data to simplify the code.
Below to found and use the two-dimension array the example:

1 #! /usr/bin/perl
2 #
3 # Using Multi-dimensional Array references
4 #
5 $line = ['solid', 'black', ['1', '2', '3'], ['4', '5', '6']];
6 print œ$line->[0] = $line->[0] n”;
7 print “$line->[1] = $line->[1] n”;
8 print “$line->[2][0] = $line->[2][0] n”;
9 print “$line->[2][1] = $line->[2][1] n”;
10 print “$line->[2][2] = $line->[2][2] n;
11 print “$line->[3][0] = $line->[3][0] n”;
12 print “$line->[3][1] = $line->[3][1] n”;
13 print “$line->[3][2] = $line->[3][2] n”;
14 print “n”; # The obligatory output beautifier.

The result output is as follows:

$line->[0] = solid
$line->[1] = black
$line->[2][0] = 1
$line->[2][1] = 2
$line->[2]ΐ] = 3
$line->[3][0] = 4
$line->[3][1] = 5
$line->[3][2] = 6

Then three-dimensional array how? Below is the edition which on the example modifies slightly.

1 #! /usr/bin/perl
2 #
3 # Using Multi-dimensional Array references again
4 #
5 $line = ['solid', 'black', ['1', '2', '3', ['4', '5', '6']]];
6 print “$line->[0] = $line->[0] n”
7 print “$line->[1] = $line->[1] n”;
8 print “$line->[2][0] = $line->[2][0] n”;
9 print “$line->[2][1] = $line->[2][1] n”;
10 print €œ$line->[2][2] = $line->[2][2] n”;
11 print “$line->[2][3][0] = $line->[2][3][0] n”;
12 print “$line->[2][3][1] = $line->ΐ][3][1] n”;
13 print “$line->[2][3][2] = $line->[2][3][2] n”;
14 print “n”;

The result output is as follows:

$line->[0] = solid
$line->[1] = black
$line->[2][0] = 1
$line->[2][1] =ł
$line->[2][2] = 3
$line->[2][3][0] = 4
$line->[2][3][1] = 5
$line->[2][3][2] = 6

Visits the third element way shape like $line->[2][3][0], is similar in C language Array_pointer[2][3][0]. In this example, the subscript is a digit, certainly also the available variable replaces. May unifies with this method the array and the Hasche table the constitution complex structure, as follows:

1 #! /usr/bin/perl
2 #
3 # Using Multi-dimensional Array and Hash references
4 #
5%cube = (
6 ’0′, ['0', '0', '0'],
7 ’1′, ['0', '0', '1'],
8 ’2′, ['0', '1', '0'],
9 ’3′, ['0', '1', '1'],
10 ’4′, ['1', '0', '0'],
11 ’5′, ['1', '0', '1'],
12 ’6′, ['1', '1', '0'],
13 ’7′, ['1', '1', '1']
14);
15 $pointer = %cube;
16 print “n Da Cube n”;
17 foreach $i (sort keys %$pointer) {
18 $list = $$pointer{$i};
19 $x = $list->[0]
20 $y = $list->[1];
21 $z = $list->[2];
22 printf “Point $i = $x,$y,$z n”;
23}

The result output is as follows:

Da Cube
Point 0 = 0,0,0
Point 1 =ŀ,0,1
Point 2 = 0,1,0
Point 3 = 0,1,1
Point 4 = 1,0,0
Point 5 = 1,0,1
Point 6 = 1,1,0
Point 7 = 1,1,1

This is a definition cube example. in what %cube preserves is the comma and the coordinate, the coordinate is contains three digital arrays. Variable $list gain coordinate array quotation: $list = $$ pointer{$i}; Then visits various coordinate figures: $x = $list->[0]; … also the available following method gives $x, $y and the $z evaluation: ($x,$y,$z) = @$list;

When use Hasche table and array, with $ and with – > is similar, the following two sentences speaking of the array equivalent:

$$names[0] = “kamran”;
$names->[0] = “kamran”;

The following two sentences speaking of the Hasche table equivalent:
$$lastnames {“kamran”} = “Husain”;
$lastnames-> {“kamran”} = “Husain”;

In the Perl array may in the movement the foundation and the expansion. When the array quotation first time appears when the equality, this array is founded automatically, the simple variable and the multi-dimensional array are also same. Following sentence, if array contours does not exist, is founded:

$contours[$x][$y][$z] = &xlate ($mouseX, $mouseY);

Sixth, subroutine quotation

in perl in the subroutine quotation and C the function indicator is similar, the structure method is as follows:

$pointer_to_sub = sub {… declaration of sub…};

Through
the call by reference subroutine’s method which constructs is:

&$pointer_to_sub(parameters);

Subroutine template

The subroutine returns value is not only restricted in the data, but may also return to the subroutine the quotation. The returns subroutine is adjusting the use execution, but is actually in the accent use which founds is established at first, this is by Perl the way decision which processes to Closure. Closure Italy namely, if you have defined a function, it by the content movement which at first defines. (Closure for details sees OOP the reference book) in the following example, has established many error message demonstration subroutine, such subroutine definition method may use in founding the template.

#! /usr/bin/perl
sub errorMsg {
my $lvl = shift;
#
# define the subroutine to run when called.
#
return sub {
my $msg = shift; # Define the error type now.
print œErr Level $lvl:$msgn”; }; # print later.
}
$severe = errorMsg (“Severe”);
$fatal = errorMsg (“Fatal”);
$annoy = errorMsg (“Annoying”)

&$severe (“Divide by zero);
&$fatal (“Did you forget to use a semi-colon?”);
&$annoy (“Uninitialized variable in use€)

The result output is as follows:

Err Level Severe:Divide by zero
Err Level Fatal:Did you forget to use a semi-colon?
Err Level Annoying:Uninitialized variable in use

On the example, subroutine errorMsg has used confined variable $lvl, uses in returning to the transfer. When errorMsg is transferred, the $lvl value establishes to the returns subroutine content, although is the my function which uses. Three transfers have established three different $lvl variable values. When errorMsg returns, the $lvl value preserves was stated each time when produces in subroutine code. Finally three pair process’s subroutine quotations carry on when the transfer the $msg value is replaced, but the $lvl value was still time the corresponding subroutine code foundation value.

Confuses very much right? Yes, therefore such code is very rare in the Perl procedure.

Seventh, array and subroutine

The array favors the management correlation data, how does this festival discuss transmits many arrays to the subroutine. Front we have said with @ the _ transmission subroutine parameter, but @ _ is an e-dimensional array, no matter you transmit the parameter is how many arrays, according to sequence stores in @ _, therefore uses shape like my(@a,@b)=@_; When the sentence gains the parameter value, the complete value tax has given @a, but @b is spatial. How then to transmit an above array for the subroutine? The method is with the quotation. Sees as follows:

#! /usr/bin/perl
@names = (mickey, goofy, daffy);
@phones = (5551234, 5554321, 666)
$i = 0;
sub listem {
my ($a,$b) = @_;
foreach (@$a) {
print “a[$i] =”. @$a[$i]. ““. “tb[$i] =”. @$b[$i]. “n”;
$i++;
}
}
&listem (@names, @phones);

The result output is as follows:

a[0] = mickey b[0] = 5551234
a[1] = goofy b[1] = 5554321
a[2] = daffy b[2] = 666

Attention:

1st, when certainly wants to transmit is more than a array for the subroutine parameter must use the quotation.
2nd, certainly do not use the shape in the subroutine like (@variable) =@_; Sentence processing parameter, only if you want to concentrate all parameters to a long array.

Eighth, document handle quotation

Sometimes, must output the identical information the different document, for example, some procedure possibly outputs the screen in an example, another outputs the printer, another outputs the record file, even simultaneously outputs these three documents. Compares at each kind of processing writes an independent sentence, may have well realizes the way to be as follows:

spitOut(*STDIN);
spitOut(*LPHANDLE);
spitOut(*LOGHANDLE);

And the subroutine spitOut code is as follows:

sub spitOut {
my $fh = shift;
print $fh “Gee Wilbur, I like this lettucen”;
}

The attention document handle quotation’s grammar is *FILEHANDLE.


The 11th chapter filing system

This chapter says the function has used the UNIX operating system’s characteristic most, when the non-UNIX system, some functions possibly does not have the definition or has the different working, the use please to examine the Perl on-line documents.

First, document input/output function

This festival narrates from the document reads the information and to the file write information built-in storehouse function.

1st, basic I/O function

Some I/O function had the narration in the front chapter, like

open: Permission procedure visit document
close: Termination file archive
print: File write string of character
write: To file write formatting information
printf: The formatted string of character and outputs the document

Here reviews simply, speaks the function which again some front had not mentioned.

1) open function

the open function relates the document variable with some document, provides the visit document the connection, for example: open (MYVAR, “/u/file) If the document opens successfully, then returns non-zero value, otherwise returns zero. Default, open opens the document to use to read its content, if wants to open the document to read in the content, adds before the filename to be bigger than the number: open (MYVAR, â€>/u/file”); Increases the content to the existing document end to be bigger than the number with two: open (MYVAR, “>>/u/file”); If wants to open the document to take the data guidance the order, adds on the pipeline symbol before the order (|): open (MAIL, “|mail dave”);

2) inputs with the open heavy direction detection

May the document handle which opens serve as to the procedure data-in order, the method is in the order add-on pipeline symbol (|), for example:

open (CAT, “cat file*|”);

To open transfer run command cat file*, this order founds a temporary file, this document’s content is possesses by the file drivehead’s document content connection becomes, this document regards as the input file, available document variable CAT visit, for example:

$input = ;

The following example use orders all user which w loses lists current registers.

1: #! /usr/local/bin/perl
2:
3: open (WOUT, “w|”);
4: $time = ;
5: $time =~ s/^ *;
6: $time =~ s/. *;
7: ; # skip headings line
8: @users = ;
9: close (WOUT);
10: foreach $user (@users) {
11: $user =~ s/. *;
12: }
13: print (“Current time: $time”);
14: print (€œUsers logged on:n”);
15: $prevuser = “”;
16: foreach $user (sort @users) {
17: if ($user ne $prevuser) {
18: print (“t$user”);
19: $prevuser = $user;
20: }
21: }

The result output is as follows:

Current time: 4:25 pm
Users logged on:
dave
kilroy
root
zarquon

the w order lists the user who the current time, the system load and register, as well as each user’s operating time and current movement order, for example:

4:25 pm up 1 day, 6:37, 6 users, load average: 0.79, 0.36, 0.28
User tty login@ idle JCPU PCPU what
dave ttyp0 2ᛂ pm 27 3 w
kilroy ttyp1 9:01 am 2:27 1:04 11 – csh
kilroy ttyp2 9:02 am 43 1:46 27 rn
root ttyp3 4:22 pm 2 – csh
zarquon ttyp4 1:26 pm 4 43 16 cc myprog.c
kilroy ttyp5 9:03 am 2:14 48 /usr/games/hack

On the example takes out the information which from the w order’s output needs: The current time and registers user. The 3rd line moves the w order, here assigns w to the open transfer the output to serve as the procedure the input, visits this input with document variable WOUT. The 4th line reads the first line of information, namely:

4:25 pm up 1 day, 6:37, 6 users, load average: 0.79, 0.36, 0.28

The two lines then extract the time from this line. First, the 5th line of deletion outset’s blank space, then the 6th line obliterates except the time and the ending line feeds between symbol all characters, stores variable $time.

The 7th line reads the second line from WOUT, in this line has nothing with the information, therefore does not make processing. The 8th line the good tax which is left over for array @users, then the 9th line closes WOUT, the termination moves the w order advancement.

in @users each element is a line of user information, because this procedure only needs each line of first word, namely user, therefore 10~12 lines remove besides line feed symbol other characters, after this end of loop, in @users is only left over a user tabulation.

The 13th line of output storage in the $time time, the attention print did not need to add on by now line feeds the symbol, because in $time has. 16~21 lines sort to @users user and output. Because the identical user may register many times, therefore stores the output with $preuser last user, when next time output array element $user, if it is equal with $preser, then does not output.

3) document heavy direction detection

Many UNIX shell may standard output document (STDOUT) and the standard wrong document (STDERR) heavy direction detection to the identical document, for example in Bourne Shell (sh), the order

$ foo > file1 2>&1

Run command foo and outputs the standard output document and the standard wrong document content stores to document file1. Below is realizes this function example with Perl:


1: #! /usr/local/bin/perl
2:
3: open (STDOUT, “>file1”) || die (“open STDOUT failed”);
4: open (STDERR, “>&STDOUT”) || die (“open STDERR failedâ);
5: print STDOUT (“line 1n”);
6: print STDERR (“line 2n”);
7: close (STDOUT);
8: close (STDERR);

After the movement, in the document file1 content is:
line 2
line 1

May see that these two lines not the smooth storage which imagines according to us, why? We analyze this section of procedures.

The 3rd line of heavy directional standard output document, the method is opens document file1 it with the document variable STDOUT connection, this has also closed the standard output document. The 4th line of heavy directional standard wrong document, parameter >&STDOUT tells the Perl interpreter use to open and with the STDOUT connection document, namely document variable STDERR direction and STDOUT same document. The 5th, 6 lines separately to STDOUT and STDERR write data, because these two document variable direction identical document, therefore two lines of strings of character write about in document file1, but the order is actually wrong, how matter?

The question lies in UNIX to the output in processing. When uses print (or other functions) read in documents and so on STDOUT, what the UNIX operating system truly does is the data copy to a piece of special memory is in a buffer, the output operation then continues to read in the buffer until to write all over, when the buffer has filled, complete data actual output. Reads in the buffer the time which spends compared to each time the actual output to like this first be short again a lot the entire buffer content output, because of generally speaking, I/O operates the memory is much slower.

When the procedure ended, any non-spatial buffer is output, however, the system was STDOUT and STDERR maintains a stretch of buffer separately, and output STDERR the first content, therefore stored in STDERR buffer content line 2 appears in the storage before in STDOUT buffer content line 1.

In order to solve this problem, may tell the Perl interpreter to the document use cushion, the method is not:

1st, chooses the document with the select function
2nd, 1 bestows on the value for the system variable $|

System variable $|Assigns the document whether to carry on the cushion no matter, but it whether should use the cushion. If $|Does not use the
cushion for the non-zero value. $|With system variable $~ and $^ joint operation, when has not transferred the select function, $|Influence current default file. Has guaranteed the output order as follows:

1: #! /usr/local/bin/perl
2:
3: open (STDOUT, “>file1”) || die (“open STDOUT failed”);
4: open (STDERR, “>&STDOUT”) || die (“open STDERR failed”);
5: $| = 1;
6: select (STDERR);
7: $| = 1;
8: print STDOUT (“line 1n”);
9: print STDERR (“line 2n”);
10: close (STDOUT);
11: close (STDERR);


After program run, in document file1 the content is:
line 1
line 2

5th about to $|Bestows on 1, tells the Perl interpreter current default file not to carry on the cushion, because has not transferred select, current default file for heavy direction detection to document file1 STDOUT. The 6th about to current default file supposes is STDERR, the 7th line establishes $|For 1, has switched off the heavy direction detection to the file1 standard wrong document cushion. Because STDOUT and the STDERR cushion is switched off, is written immediately to its output in the document, therefore line 1 appears in the first line.

4) assigns the read-write jurisdiction

Opens one both to be possible to read the document method which, and may write is before the filename adds on ” +> “, as follows:

open (READWRITE, “+>file1”);

This sentence opens both may read document filϳ which, and may write, namely may rewrite content. The document read-write operation should better uses together with storehouse function seek and tell, like this may jump to document any spot.

Note: Also the available prefix ” +< " assigns to be possible the read-write jurisdiction.

5) close function

Uses in document which closes opens. When closes the pipeline with close, when namely heavy directional order, the procedure waited for heavy directional the order conclusion, for example:
open (MYPIPE, “cat file*|”);
close (MYPIPE);

When closes this document variable, the program suspension movement, until ordered cat the file* movement to finish.

6) print, printf and write function

print is in these three functions the simple, it to the document output which assigns, if has not assigned, then outputs in the current default file, for example:

print (“Hello, there! n”);
print OUTFILE (“Hello, there! n);

First outputs in the current default file, if has not transferred select, is STDOUT. Second outputs in the document which assigns by document variable OUTFILE.

the printf function the formatted string of character outputs again first assigns in the document or the current default file, for example:
printf OUTFILE (“You owe me %8.2f”, $owing);

This sentence takes out variable $owing the value and replaces in the string %8.2f,%8.2f is the territory form example, regards as the floating number the $owing value.

the write function use output format outputs the information in the document, for example:
select (OUTFILE);
$~ = “MYFORMAT”;
write;

About printf and write, for details see “xth Chapter of Formatted Output”.

7) select function

the select function will assign through the parameter transmission’s document variable for the new current default file, for example:
select (MYFILE);

Thus, MYFILE has become the current default file, when to print, write and the printf transfer has not assigned the document, outputs in MYFILE.

8) eof function

the eof function examined that last time reads the file operation whether for document last record, if is, then returns non-zero value, if the document also has the content, returns zero.

In the ordinary circumstances, does not add the parenthesis to the eof transfer, because eof and eof() are equivalent, but uses together with the <> instruction character time, eof and eof() were different. Now we found two documents, is called file1 and file2 separately. the file1 content is:

This is a line from the first file.
Here is the last line of the first file.

the file2 content is:

This is a line from the second and last file.
Here is the last line of the last file.

Below looked that eof and the eof() difference, the first procedure is:

1: #! /usr/local/bin/perl
2:
3: while ($line = <>) {
4: print ($line);
5: if (eof) {
6: print (“– end of current file –n”);
7: }
8: }

The movement result is as follows:

$ program file1 file2
This is a line from the first file.
Here is the last line of the first file.
– end of current file –
This is a line from the second and last file.
Here is the last line of the last file.
– end of current file –
$

Below changes eof eof(), the second procedure is:


1: #! /usr/local/bin/perl
2:
3: while ($line = <>) {
4: print ($line);
5: if (eof()) {
6: print (“– end of output –n”);
7: }
8: }

The movement result is as follows:


$ program file1 file2
This is a line from the first file.
Here is the last line of the first file.
This is a line from the second and last file.
Here is the last line of the last file.
– end of output –$

By now, only then all documents had read, eof() only then returns real, if is only in many documents first several end, the returns value is a vacation, because also has the input which must read.

9) indirect file variable

Regarding above various functions open, close, print, printf, write, select and eof, may use the simple variable to replace the document variable, by now, in the simple variable stored the string of character is regarded as document variable, below is this kind of example, this example is very simple, did not explain. What needs to point out that function open, close, write, select and eof also allow with the expression to substitute the document variable, the expression value must be strings of character, serves as document variable.


1: #! /usr/local/bin/perl
2:
3: &open_file (“INFILE”, “”, “file1”);
4: &open_file (“OUTFILE”, “>”, “file2â);
5: while ($line = &read_from_file (“INFILE”)) {
6: &print_to_file (“OUTFILE”, $line);
7: }
8:
9: sub open_file {
10: local ($filevar, $filemode, $filename) = @_;
11:
12: open ($filevar, $filemode. $filename) ||
13: die (“Can’t open $filename”);
14: }
15: sub read_from_file {
16: local ($filevar) = @_;
17:
18: <$filevar>;
19: }
20: sub print_to_file {
21: local ($filevar, $line) = @_;
22:
23: print $filevar ($line);
24: }

2nd, jump and stress data


Letter proper name seek
Transfer grammar seek (filevar, distance, relative_to);
Illustration After document forward/moves, has three parameters:
1st, filevar, document variable
2nd, distance, motion byte count, positive number forward motion, negative number round trip migration
3rd, reletive_to, the value may be 0, 1 or 2. When for 0, starts from the article article to move, when is 1, is opposite (next line which is going to read) in the current position moves, when is 2, is opposite moves end of the document.
Moves the successful returns really (non-zero value), the defeat returns to zero, often comes in handy with the tell function.

 

Letter proper name tell
Transfer grammar tell (filevar);
Illustration Returns from article article to current position distance.
Attention:
1st, seek and tell cannot use in aiming at pipeline’s document variable.
2nd, in seek and tell the document variable parameter may use the expression.

3rd, system read-write function


Letter proper name read
Transfer gra
mmar read (filevar, result, length, skipval);
Illustration the read function designs with the UNIX fread function equivalent, may read the random length the character (byte) to store a simple variable. Its parameter has four:
1st, filevar: Document variable
2nd, result: Storage result simple variable (or array element)
3rd, length: Read byte count
4th, skipval: The byte count but the option, before assigning to read document, jumps over.
Returns value for actual read byte count, if already to document end, then returns zero, if makes a mistake, then returns returns empty the string.

 

Letter proper name sysread
Transfer grammar sysread (filevar, result, length, skipval)
Illustration Quicker read data, with UNIX function read equivalent, the parameter and read are the same.

 

Letter proper name syswrite
Transfer grammar syswrite (filevar, data, length, skipval);
Illustration Quicker write data, with UNIX function write equivalent, parameter:
1st, filevar: Is going to read in document
2nd, data: The storage wants the write data the variable
3rd, length: Must read in byte count
4th, before skipval writes the operation, jumps over byte count.

4th, reads the character with getc


Letter proper name getc
Transfer grammar $char = getc (infile);
Illustration Reads the single character from the document.

5th, reads the binary file with binmode


Letter proper name binmode
Transfer grammar binmode (filevar);
Illustration When your system (for example the kind of DOS system) has the difference to the text document and the binary file uses. Must before opening the document, the read document use.

Second, table of contents processing function

Letter proper name mkdir
Transfer grammar mkdir (dirname, permissions);
Illustration Founds the new table of contents, the parameter is:
1st, dirname: Is going to found the table of contents name, may for the string of character or the expression
2nd, permissions:8 enters the system number, assigns the table of contents the access authority, its value and the significance will see the next table, the jurisdiction combined method for corresponding value adding together.



Value Jurisdiction
4000 When movement establishes user ID
2000 When movement establishes group ID
1000 Glue position
0400 The owner reads the jurisdiction
0200 The owner writes the jurisdiction
0100 The owner carries out the jurisdiction
0040 The group reads the jurisdiction
0020 The group writes the jurisdiction
0010 The group carries out the jurisdiction
0004 All people read the jurisdiction
0002 All people write the jurisdiction
0001 All people carry out the jurisdiction



Letter proper name chdir
Transfer grammar chdir (dirname);
Illustration Change current job category. Parameter dirname may be a string of character, may also be an expression.



Letter proper name opendir
Transfer grammar opendir (dirvar, dirname);
Illustration Opens the table of contents, comes in handy with the following several functions, may examine in some table of contents the listed files. The parameter is:
1st, dirvar: The table of contents variable, is similar with the document variable
2nd, dirname: Table of contents name, but is the string of character or the expression
Success returns true value, defeat returns vacation.
Note: In procedure available table of contents variable and document variable of the same name, according to the environment determined that takes the ingredient.



Letter proper name closedir
Transfer grammar closedir (mydir);
Illustration The closure opens table of contents.



Letter proper name readdir
Transfer grammar readdir (mydir);
Illustration When bestows on for the simple variable, each time entrusts with a document or child directory, entrusts with the complete document and child directory to the array.



Letter proper name telldir
Transfer grammar location = telldir (mydir);
Illustration The shuttle is likely same in the document, telldir and following seekdir use in the table of contents tabulation the shuttle.



Letter proper name seekdir
Transfer grammar seekdir (mydir, location);
Illustration location must be the telldir returns value.



Letter proper name rewinddir
Transfer grammar rewinddir (mydir);
Illustration Will read the table of contents the position reset to return to the opening, thus may the stress table of contents tabulation.



Letter proper name rmdir
Transfer grammar rmdir (dirname);
Illustration Deletes the spatial table of contents. The success returns to really (non-zero value), the defeat returns to (zero value) false.

Third, file attribute function

1st, document heavy mapping function


Letter proper name rename
Transfer grammar rename (oldname, newname);
Illustration The change filename or moves to another table of contents, the parameter may for the string of character or the expression.



Letter proper name unlink
Transfer grammar num = unlink (filelist);
Illustration Delete files. The parameter is the filename tabulation, the returns value for the actual deletion document number.
The reason that this function calls unlink not to call delete is because it does is actually the delete files link.

2nd, link and mark link function


Letter proper name link
Transfer grammar link (newlink, file);
Illustration Founds the existing document the link–The hard link, file is the document which links, newlink is the link which founds.
The success returns real, defeat returns vacation.
When deletes in these two links, but may also use another to visit this document.



Letter proper name symlink
Transfer grammar symlink (newlink, file);
Illustration Founds the existing document the mark link, namely directional filename, but is not aims at the document itself. Parameter and returns value with on.
When the original document is deleted (for example: By the unlinke function deletion), is founded the link not available, only if founds one again with originally the document document which of the same name links.



Letter proper name readlink
Transfer grammar filename = readlink (linkname);
Illustration If linkname is the mark chained file, returns to its actual directional the document. Otherwise returns returns empty the string.

3rd, document permission weighting function



Letter proper name chmod
Transfer grammar chmod (permissions, filelist);
Illustration Change document access authority. The parameter is:
1st, permissions is the jurisdiction which is going to establish, its meaning sees in above mkdir the jurisdiction table
2nd, filelist is wants to change the jurisdiction the listed files



Letter proper name chown
Transfer grammar chown (userid, groupid, filelist);
Illustration The change document is a host, has three parameters:
1st, userid: Is newly main (digit) the ID number
2nd, groupid: The new group (digit) the ID number, – 1 to retain the original group
3rd, filelist: Wants to change is the main listed files



Letter proper name umask
Transfer grammar oldmaskval = umask (maskval);
Illustration The establishment file archive jurisdiction mask, the returns value is the current mask.

4th, other attribute function


Letter proper name truncate
Transfer grammar truncate (filename, length);
Illustration Reduces the document length to the length byte. If the document length were smaller than already length, then does not do any matter. And filename may be a filename, may als
o be the document variable



Letter proper name stat
Transfer grammar stat (file);
Illustration Gain document condition. Parameter file may be the filename may also be the document variable. The returns list element is in turn:

Document in equipment
Materials for internal reference number (inode)
Access authority
Hard link number
Is main (digit) ID
Respective group (digit) ID
Device type (, if file is equipment)
Document size (byte count)
Finally access time
Finally the revision time changes the condition time finally
I/O operates the best block size
Assigns for this document block number




Letter proper name lstat
Transfer grammar lstat (file);
Illustration Is similar with stat, the difference is regards as file is the mark link.

 

Letter proper name time
Transfer grammar currtime = time();
Illustration The returns accumulates a second number from January 1, 1970.



Letter proper name gmtime
Transfer grammar timelist = gmtime (timeval);
Illustration By time, stat or – A and – M document test instruction character returns time reversal Greenwich Mean Time. The returns list element is in turn:

Second
Minute
Hour, 0~23
Date
Month, 0~11 (in January ~ in December)
Year
Week, 0~6 (Sunday ~ Saturday)
One year date, 0~364
Whether summertime’s symbol
For details sees UNIX the gmtime help.




Letter proper name localtime
Transfer grammar timelist = localtime (timeval);
Illustration Is similar with gmtime, distinguishes to transform the time value into the local time.



Letter proper name utime
Transfer grammar utime (acctime, modtime, filelist);
Illustration The change document’s final access time and changes the time finally. For example:
$acctime = – A “file1”;
$modtime = – M “file1”;
@filelist = (“file2”, “file3”);
utime ($acctime, $modtime, @filelist);



Letter proper name fileno
Transfer grammar filedesc = fileno (filevar);
Illustration Returns document internal UNIX document description. Parameter filevar is the document variable.



Letter proper name fcntl
flock
Transfer grammar fcntl (filevar, fcntlrtn, value);
flock (filevar, flockop);
Illustration For details sees the UNIX function help of the same name.


Fourth, uses the DBM document

In Perl the available connection array visits the DBM document, uses the function is dbmopen and dbmclose, in Perl5, already replaces with tie and untie.

Letter proper name dbmopen
Transfer grammar dbmopen (array, dbmfilename, permissions);
Illustration Will be connected the array and the DBM document is connected. The parameter is:
1st, array: Uses the connection array
2nd, dbmfilename: Will open DBM filename
3rd, the access authority, for details sees mkdir


Letter proper name dbmclose
Transfer grammar dbmclose (array);
Illustration Closes the DBM document, the demolition connection array with it relations.


  • Copyright © 1996-2010 Programming tutorials for beginners,. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress