当前位置:网站首页>Brief introduction of Perl language

Brief introduction of Perl language

2022-07-23 19:08:00 qq_ forty-four million nine hundred and eighty-five thousand si

1.Hello,World

#!/usr/bin/perl -w
print  ( "hello,world!\n" );
#print "hello,world!\n";

explain :

(1) The first line specifies the interpreter ,-w Parameter indicates prompt warning ( Or use use strict command , perform More stringent inspection );
(2) The second line outputs hello,world!;
(3) If you get used to it c The function of ,print Parameters of can be bracketed ;
(4) The third line is the comment , Annotate with # Lead ;
(5) If you get used to it shell The way ,print Parameters of can be without parentheses ; (6) Escape characters can be used in double quotation marks ;

You might as well call the file helloworld.pm
The execution method of the program is :

1)perl helloworld.pm
(2)chmod 755 helloworld.pm && ./helloworld.pm

2. Constant
2.1 Numbers

1)Perl Internal general “ Double precision floating point ” Save numbers and perform operations ;
(20377=> octal ;0xFF=> Hexadecimal ;

2.2 character string

1) Single quotation marks denote strings , No escape ;
(2) Double quotes represent strings , Escape and explain variables ;

2.3 String Operators

1) Splicing operators :“.=> String concatenation ;
(2) Repeat operator :“x”=> A string repeats many times ;
#!/usr/bin/perl -w
print  ( "hello," . "world!\n" );
print  ( "hello "  x 3);
 The output is :
hello,world!
hello hello hello

Finally, let me make a point ,Perl It's a weakly typed language , Strings and numbers will be converted to each other , This and php equally .

3. Variable

1) Variables to $ start , Followed by an identifier ;
(2) How to get user input with variables ?

Use , It gets user input ( It usually ends with a newline ), have access to chomp Remove line breaks at the end .

#!/usr/bin/perl -w
$count  = 0;
while ( $count <10)
{
    
chomp ( $input  = );
print ( $input );
$count ++;
}

(3) Variable not defined
Undefined variables are assigned undef value , It's neither a number , It's not a string ;
It may be regarded as a number 0 Use ;
Use define Function can know whether a variable is defined ;

#!/usr/bin/perl -w
$var  =  undef ;
print ( $var );
if ( defined ( $var ))
{
    
print ( "defined!\n" );
}
else
{
    
print ( "undefined!\n" );
}
$var ++;
print ( $var );
 Its output is :
Use of uninitialized value in print at undef.pm line 3.
undefined!

(4) Scope of variable
my and our You can specify the scope of the variable
my Specify as local scope ;
our Specify as global scope ( The default is our);

#!/usr/bin/perl -w
our  $g_one  =  "global_one\n" ;
$g_two  =  "global_two\n" ;
{
    
my  $local_one  =  "local_one\n" ;
print ( $g_one );
print ( $g_two );
print ( $local_one );
}
print ( $g_one );
print ( $g_two );
print ( $local_one );
 Output is :
global_one
global_two
local_one
global_one
global_two
Use of uninitialized value in print at our_my.pm line 13.

4. Arrays and lists
4.1 Array

and c The array usage of is very similar :

$array[0]=”a0″;
$array[1]=”a1″;
$array[2]=”a2″;

4.2 list
A series of values in parentheses , Composition list :

(1, 2, 3)
(“hello”, 4)
(“hello”, “world”, “yes”, “no”)
qw(hello world yes no)
(1..10)
 explain :
(1) first line , The list element is 1,2,3;
(2) The second line , The list element is a string , A number ;
(3) The third line , The list element is 4 A string , Lots of quotation marks and commas ;
(4) In the fourth row ,wq The operator , Used to create a string list , Instead of entering so many quotes and commas , The effect is the same (3);

(5) Range operators “…”, Represents a range , Add one continuously from left to right .

 Assignment of the list :
($v1, $v2, $v3) = qw(yes i am);

 References to the entire list ,@ The operator :
@list = qw(yes i am);
@none = ();
@huge = (1..5);
@stuff = (@list, @none, @huge);

pop and push The operator :
(1)pop Pop up the elements at the end of the list ;
(2)push Push elements into the end of the list ;

shift and unshift The operator :
(1)shift Remove the first element of the list ;
(2)unshift Push elements into the top of the list ;

Output of list :
(1) List output , Only output the list , No spaces between elements ;
(2) String output of the list , Output list , Add spaces between elements ;
(3)foreach Control results , You can get each element in the list in turn

#!/usr/bin/perl -w
@list  = qw(yes i am);
@none  = ();
@huge  = (1..5);
@stuff  = ( @list ,  @none ,  @huge );
$pop_last  =  pop ( @stuff );
print ( $pop_last );
push ( @stuff ,  "hello" );
$shift_first  =  shift ( @stuff );
print ( $shift_first );
unshift ( @stuff ,  "world" );
print ( @stuff );
print ( "@stuff" );
$element = undef ;
foreach  $element  ( @stuff )
{
    
print ( "$element!\n" );
}
 Output :
5
yes
worldiam1234hello
world i am 1 2 3 4 hello
i!
am!
1!
2!
3!
4!
hello!

**4.3 The default variable ∗ ∗ Where variables should be used , If you omit variables , The default variable will be used _** Where variables should be used , If you omit variables , The default variable will be used Where variables should be used , If you omit variables , The default variable will be used _.

#!/usr/bin/perl -w
$_ = "hello,world!" ;
print ();
 The output is :
hello,world!

5. function
5.1 Function definition and call

(1) The keyword defining the function is sub;
(2) The keyword of function call is &;
(3) You can use return Show return , You can also use a number to implicitly return

#!/usr/bin/perl
$num =0;
sub  sumAdd
{
    
$num +=1;
print ( "$num\n" );
#return $num; #  Show return 
$num ;  #  Implicit return 
}
&sumAdd;
&sumAdd;
print (&sumAdd);
 The execution result is :
1
2
3
3

5.2 The parameters of the function
(1) When calling a function, you can take the parameter list directly ;
(2) The function definition uses “ The default variable ” Get parameter list ;

#!/usr/bin/perl -w
sub  max
{
    
return  ( $_ [0]> $_ [1]? $_ [0]: $_ [1]);
}
$big =20;
$small =10;
print (&max( $big , $small ));
 Output is :
20

6. Program input and output
Standard input has been described above , Here are several other common inputs and outputs .
6.1Unix Tool input and output :
Offer something similar to Unix Function of tool input and output , The functions it provides can be very good with cat/sed/awk/sort/grep And other tools .

#!/usr/bin/perl -w
use  strict;
while (<>)
{
    
chomp ();
print ( "$_!!!\n" );
}

The function of the script , Is to add !!!, It uses default variables in several places .
You might as well call the file diamond.pm
Might as well set hello.txt There are three lines of data in , Namely 111,222,333
Execution steps :

1)chmod 755 diamond.pm
(2)cat hello.txt | ./diamond.pm | cat
 Output results :
111!!!
222!!!
333!!!

6.2 Format output :printf

#!/usr/bin/perl -w
$int_var  = 2011;
$str_var  =  "hello,world" ;
printf ( "%d\n%s\n" , $int_var , $str_var );
 The output is :
2011
hello,world

6.3 File input and output
Perl Retain the 6 File handles :STDIN/STDOUT/STDERR/DATA/ARGV/ARGVOUT
Above 6.1 The program in can be executed like this :
./diamond.pm out.txt
The output will be redirected to out.txt in

Input and output to file , Need to open 、 Use 、 Close the file handle

1) Open the file handle :
open LOG,>>log.txt”;
open CONFIG, ” (2) Close the file handle :
close LOG;
close CONFIG;3) Use file handles :
print LOG (“hello,world!\n”);
print STDERR (“yes i am!\n”);
while()
{
    
chomp();}

 You can also use select keyword :
print(“to stdout1!);
select LOG;
print(“to log1″);
print(“to log2″);
select STDOUT;
print(“to stdout2!);
#!/usr/bin/perl -w
$input_file  =  "hello.txt" ;
$output_file  =  "out.txt" ;
open  INPUT,  "<$input_file" ;  open  OUTPUT,  ">>$output_file" ;
while (
<input type= "text" >)
{
    
chomp ();
print  OUTPUT ( "$_!!!\n" );
}
close  OUTPUT;
close  INPUT;

explain : Its functions are the same as those before diamond.pm It's the same .

7. Hash hash
7.1 Hash access

$key=”am”;
$hash_one{
    “yes”} = 3;
$hash_one{
    “i”} = 1;
$hash_one{
    $key} = 5;
print($hash_one{
    “am”});
$value = $hash_one{
    “hello”}; # undef

7.2 Hash reference

 To reference the entire hash , Use % The operator .
%hash_one = (“hello”,5,”world”,5);
print ($hash_one{
    “hello”});
%hash_two = %hash_one;

7.3 Unbinding hash
Hash can be converted into a list of key values , It is called the unbinding of hash , The order of keys is not guaranteed after conversion , But the value must be after the key .

#!/usr/bin/perl -w
%hash_one  = ( "hello" ,5, "world" ,5);
$hash_one {
     "yes" } = 3;
$hash_one {
     "i" } = 1;
$hash_one {
     "am" } = 2;
@array_one  =  %hash_one ;
print  ( $hash_one {
     "hello" });
print  ( "@array_one" );
 The output is :
5
yes 3 am 2 hello 5 world 5 i 1

7.4 Inversion of hash
Establish the reverse hash of the key corresponding to the value .
%hash_reverse = reverse(%hash_one);
It works only when the key values correspond one by one , Otherwise, unexpected coverage will occur .

7.5 Aesthetic assignment of hash
The aesthetic assignment of hash uses => Symbol .

%hash_one = (“hello”,5,”world”,5,”yes”,3,”i”,1,”am”,2);
 The above assignment method is easy to make mistakes , Especially when the key values are strings .
%hash_one = (
“hello” => 5,
“world” => 5,
“yes” => 3,
“i” => 1,
“am” => 2,
);

Aesthetic assignment , Does it look more beautiful , It's easier to distinguish the key value of hash .

7.6 Hash traversal

1)keys and values Function can return a list of all keys and values , But the order in the list is not guaranteed .
@k = keys(%hash_one);
@v = values(%hash_one);2)each Function can traverse hash one by one , Return key value pair , Well suited to while Equal cycle ;
while(($key, $value) = each(%hash_one))
{
    }

Sample code :

#!/usr/bin/perl -w
%hash_one  = (
"hello"  => 5,
"world"  => 5,
"yes"   => 3,
"i"   => 1,
"am"   => 2,
);
@k  =  keys ( %hash_one );
@v  =  values ( %hash_one );
print ( "@k\n" );
print ( "@v\n" );
$key  =  undef ;
$value  =  undef ;
while (( $key ,  $value ) =  each ( %hash_one ))
{
    
print ( "$key=>$value\n" );
}
 The output is :
yes am hello world i
3 2 5 5 1
yes=>3
am=>2
hello=>5
world=>5
i=>1

7.7 Hash query and deletion
(1) Query whether a key exists , Use exists function ;
(2) Delete a key , Use delete function ;

#!/usr/bin/perl -w
%hash_one =(
"yes"   => 3,
"i"   => 1,
"am"   => 2,
);
delete ( $hash_one {
     "yes" });
if ( exists ( $hash_one {
     "yes" }))
{
    
print ( $hash_one {
     "yes" });
}

The result is nothing output .

8. Process control ( This section can be skipped , They are all fancy usages )
In addition to the commonly used in various languages if/esle,for,while Other than process control ,Perl There are also some special control statements , More human .

1)unless Control structure 
 The effect is similar to if not, Inefficiency increases , Just make the expression more natural , The code is easier to understand .
(2)until Control structure 
 The effect is similar to while not3) Conditional modification 
 The judgment condition can be written directly after the sentence , To increase readability (habadog notes : This is bullshit ).
print (“$n”) if $n < 0; $i *= 2 until $i > 1024;
&sumAdd($_) foreach @num_list;4) Bare control structure 
 There is only one curly bracket structure , It is often used to limit the scope , It is common in all languages .
{
    
$a = 1;}
 $a It doesn't work 
(5)last Control structure 
 amount to c Medium break, Terminate the loop immediately ;
(6)next Control structure 
 amount to c Medium continue, Start the next cycle immediately ;
(7)redo Control structure 
… Unique , Restart this cycle ;
while(1)
{
    
  Jump here 
print (“hello”);
redo;
}

9. Advanced features
magical Perl And regular 、module、 file 、 character string 、 Smart matching 、 Process management 、 Thread support and other advanced features , It's not introduced in the introductory manual .
If everyone likes , The manual of the above features will be released later .

原网站

版权声明
本文为[qq_ forty-four million nine hundred and eighty-five thousand si]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207231641422648.html