Perl 学习手札之七: special variables
perl uses special variable for a number of purpose.default value for function and loops
error codes and messages
information about the system and its enviroment
over 70 special variables
full list in perl documentation page "perlvar"
$_ Default input
$1, $2, $3, etc Pattern results
$! system error number or string
$@ eval() error
$$ process ID(PID)
$0 programe name
@_ list of arguments for subroutine
@ARGV list of command line arguments
@INC List of path perl searches for libraries and modules
%ENV Hash of environment variables
example.pl
#!/usr/bin/perl
use strict;
use warnings;
main(@ARGV);
sub main
{
# message(join(":",@ARGV));
message(join(":",@_));
}
sub message
{
my $m = shift or return;
print("$m\n");
}
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
this code will demo @ARGV
run this code in commandline, perl example.pl one two three four five
and the result: one: two: three: four: five
in this code, substitude the@ARGV with @_ , we will get the same result.
example1.pl
#!/usr/bin/perl
use strict;
use warnings;
main("five","six","seven");
sub main
{
# message(join(":",@ARGV));
message(join(":",@_));
}
sub message
{
my $m = shift or return;
print("$m\n");
}
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
in this code, the default array is main("five","six","seven");
example2.pl
#!/usr/bin/perl
use strict;
use warnings;
main("five","six","seven");
#main(@ARGV);
sub main
{
foreach (@_){
#foreach $_ (@_){
print;
}
}
sub message
{
my $m = shift or return;
print("$m\n");
}
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
notice: the foreach loop use default $_, 不用这个$_结果一样。
filehandle.pl
#!/usr/bin/perl
use strict;
use warnings;
main(@ARGV);
sub main
{
message("This is the template.pl exercise file from Perl 5 Essential Training.");
error("This is the template.pl exercise file from Perl 5 Essential Training.");
}
sub message
{
my $m = shift or return;
#print(STDOUT "$m\n");
print(STDOUT "$m\n");# if we want to redirect the output">", STDERR will not get it
}
sub error
{
my $e = shift || 'unkown error';
print(STDERR "$0: $e\n");
exit 0;
}
notice: the default output is STDOUT.
if we replace the STDOUT with STDERR, 我们将得到一个报错的结果: 文件名+报错信息。
filehandle1.pl
#!/usr/bin/perl
use strict;
use warnings;
main(@ARGV);
sub main
{
while(<>){
print "$. $_ ";
}
}
notice: $. represent line No
或者我们可以用直接一个print 语句,则默认输出$_。
constant.pl
#!/usr/bin/perl
use strict;
use warnings;
main(@ARGV);
sub main
{
message("the filename is ". __FILE__);
message("the line number is : ". __LINE__);
message("the package is ". __PACKAGE__);
}
#__END__
sub message
{
my $m = shift or return;
print("$m\n");
}
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
__END__
notice: __END__ is end of this script label.
页:
[1]