加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl的几个小知识点

发布时间:2020-12-16 00:01:05 所属栏目:大数据 来源:网络整理
导读:1 关于自己编写模块时在模块结尾的1;语句 这是因为当别的模块中引用该模块的时候,use 相当于可执行语句,为了在语句最后返回为true,因此加上语句1;实际上你可以写任何返回值为true的表达式 2 use和require的不同 先看perl FAQ上的回答 The use statementis

1 关于自己编写模块时在模块结尾的1;语句

这是因为当别的模块中引用该模块的时候,use 相当于可执行语句,为了在语句最后返回为true,因此加上语句1;实际上你可以写任何返回值为true的表达式


2 use和require的不同

先看perl FAQ上的回答


The use statementis the same as arequire run at compile-time,but Perl also calls theimport method for the loaded package. These two are the same:

 
 
  1. use MODULE qw(import list);
  2. BEGIN {
  3. require MODULE;
  4. MODULE->import(import list);
  5. }

However,you can suppress the import by using an explicit,empty import list. Both of these still happen at compile-time:

 
 
  1. use MODULE ();
  2. BEGIN {
  3. require MODULE;
  4. }

Since use will also call theimport method,the actual valueforMODULE must be a bareword. That is,use cannot load filesby name,althoughrequire can:

 
 
  1. require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!

See the entry for use inperlfunc for more details.


use是最常用的方式,use通常跟的是模块的名称而不是文件的名称,在编译的时候发生,有可能抛出异常,会自动调用import方法。require也是在编译的时候运行但不会自动运行import方法,当需要加载的模块比较大而仅仅使用较少方法的时候require是个不错的选择,

3 perl shift 和unshift之间的区别:

shift就是把一个数组【1,2,3,4,。。。】中的第一个元素1 拿出来,同时减少数组的大小

unshift则是相反,把上面的数组看着是可以操作的栈,在1前面再加一个元素,如【0,1,2.。。。。】


4 perl qq qw q 等之间的区别:

简单的说

q就是相当于单引号,内插变量输出不变为对应的变量的值

qq{foobar}的意思为意思为双引号字符串,可内插变量
相当于 "foobar"
qw{foo bar}的意思为用空格分解字符串,得到列表,相当于如下语句
split(' ','foo bar') 得到的结果是'foo','bar'


Quotation marks are fairly ubiquitous in Perl,as in most programming languages. Different methods of quoting exist,and each has different uses and a different set of behaviors associated with it.

This document is intended as a treatment of the subject of delimiting strings — "quoting". I try to keep it from devolving into lengthy digressions on tangential topics,such as escape characters and interpolation. Such topics do tie in with the use of such delimiters,however,and must to some degree be addressed. Further information can be found atperlop.

5 Our和my的区别:


Great question: How does our differ frommy and what does our do?

In Summary:

Available since Perl 5,my is a way to declare:

  • non-package variables,that are
  • private,
  • new,
  • non-global variables,
  • separate from any package. So that the variable cannot be accessed in the form of$package_name::variable.


On the other hand,our variables are:

  • package variables,and thus automatically
  • global variables,
  • definitely not private,
  • nor are they necessarily new; and they
  • can be accessed outside the package (or lexical scope) with thequalified namespace,as$package_name::variable.


Declaring a variable with our allows you to predeclare variables in order to use them underuse strict without getting typo warnings or compile-time errors. Since Perl 5.6,it has replaced the obsoleteuse vars,which was only file-scoped,and not lexically scoped as isour.

For example,the formal,qualified name for variable $x inside package main is $main::x. Declaring our $x allows you to use the bare$x variable without penalty (i.e.,without a resulting error),in the scope of the declaration,when the script usesuse strict or use strict "vars". The scope might be one,or two,or more packages,or one small block.



single-quotes

Single quotation marks are used to enclose data you want taken literally. Just as the <code></code> tags here at the Monastery make all text they enclose literally rendered,whitespace and all,so too does a set of single-quotes in Perl ensure that what they enclose is used literally:
  
  
#!/usr/bin/perl -w use strict; my $foo; my $bar; $foo = 7; $bar = 'it is worth $foo'; print $bar;
[download]

This example,when run,produces the following:
it is worth $foo



double-quotes

Double quotation marks are used to enclose data that needs to be interpolated before processing. That means that escaped characters and variables aren't simply literally inserted into later operations,but are evaluated on the spot. Escape characters can be used to insert newlines,tabs,and other special characters into a string,for instance. The values,or contents,of variables are used in double-quoted strings,rather than the names of variables. For instance:
  
  
#!/usr/bin/perl -w use strict; my $foo; my $bar; $foo = 7; $bar = "it is worth $foo"; print $bar;
[download]

This example,produces the following:
it is worth 7

Double-quotes interpolate scalar and array variables,but not hashes. On the other hand,you can use double-quotes to interpolate slices of both arrays and hashes.


escape characters

The interpolating effects of double-quotes creates a necessity of using escaped characters to reproduce characters within a string that would be displayed literally within single-quotes,however. For instance,to add quotes to the above-printed string in the double-quote example,you would have to do something like this:
  
  
#!/usr/bin/perl -w use strict; my $foo; my $bar; $foo = 7; $bar = "it is "worth" $foo"; print $bar;
[download]

The backslash "escapes" the quotation mark that follows it,so that running the above produces the following:
it is "worth" 7

An exception to the literal interpretation behavior in the use of single-quotes is when you wish to include single-quotes inside the string. In that case,you must escape the single-quotes you want inside the string so the Perl compiler can discern between them and the single-quotes that delimit the string:
  
  
#!/usr/bin/perl -w use strict; my $foo; my $bar; $foo = 7; $bar = 'it is 'worth' $foo'; print $bar;
[download]

This example,produces the following:
it is 'worth' $foo

In any interpolating quotation scheme,such as double-quotes (or qq and interpolating uses of <<,as described below),@ and $ characters must be escaped when you want them used literally. If they are not,they will be treated by the Perl compiler as indicators of variable names.


quoting without quotes

In Perl,you can use methods other than quotation marks to "quote" a string. This functionality makes using strings that contain quotation marks much easier sometimes,since those quotation marks no longer need to be escaped. There are three simple methods of doing this with the letter q.

In the following three sections,on the subjects of q,qq,and qw notation,I refer exclusively to the use of parentheses as delimiters. Other delimiters can be used,which allows you to avoid having to escape the characters you choose to use as delimiters if you must also include instances of them in your string. For instance,instead of using parentheses,you could also use brackets ( [ ] ),braces ( { } ),asterisks ( * * ),and (almost?) any other characters other than whitespace. It's worth noting that in the case of an alphanumeric character there must be a space between the q (or qw,or qq) and the character in question.


q

The first way to quote without quotes is to use q() notation. Instead of using quotation marks,you would use parentheses with a q preceding them:
  
  
#!/usr/bin/perl -w use strict; my $foo; my $bar; $foo = 7; $bar = q(it is 'worth' $foo); print $bar;
[download]

This example,produces the following:
it is 'worth' $foo

The q() function works the same as single-quoting your string,with the exception that you no longer need to escape single-quotes that appear within the string. You would,have to escape any parentheses you need in the string.


qq

In the same way that double-quotes add interpolation to the functionality of single-quotes,doubling the q adds interpolation to quoting without quotation marks. For instance,if you wanted to avoid escape characters and interpolate $foo in the above code,and wanted to use double-quotes around the word worth,you might do this:
  
  
#!/usr/bin/perl -w use strict; my $foo; my $bar; $foo = 7; $bar = qq(it is "worth" $foo); print $bar;
[download]

This example,produces the following:
it is "worth" 7



qw

You can use qw to quote individual words without interpolation. Use whitespace to separate terms you would otherwise have to separate by quoting individually and adding commas. This is often quite useful when assigning lists to array variables. The two following statements are equivalent:
  
  
@baz = ('one','two','three'); @baz = qw(one two three);
[download]



here documents

If you want to quote many lines of text literally,you can use "Here Document" notation. This consists of an introductory line which has two less-than signs (aka "angles" or "angle brackets": << ) followed by a keyword — the end tag — for signalling the end of the quote. All text and lines following the introductory line are quoted. The quote ends when the end tag is found,by itself,on a line. For example,if the end tag is EOT:
  
  
#!/usr/bin/perl -w use strict; my $foo = 123.45; my $bar = "Martha Stewedprune"; print <<"EOT"; ===== This is an example of text taken literally except that variables are expanded where their variable names appear. foo: $foo bar: $bar EOT
[download]

This example,produces the following:
  
  
===== This is an example of text taken literally except that variables are expanded where their variable names appear. foo: 123.45 bar: Martha Stewedprune
[download]

The type of quotation marks placed around the end tag is important. For instance,in the above example,EOT is double-quoted,and as a result the values of $foo and $bar are substituted for the variable names. Double-quoting the end tag causes the quoted block of text to be interpolated as it would be with double-quotes. Use of single-quotes would cause it to be used literally,without interpolation,as though the quoted block of text were delimited by single-quotes rather than being referenced as a "here document". Omitting the quotation marks entirely defaults to behavior the same as using double-quotes.

some notes to keep in mind:
  • The end tag specifier must follow the << without any intermediate space.
  • The actual end tag must be exactly the same as specified in the introduction line.
  • The introduction line must end with a semicolon.
The use of here documents is particularly useful in Perl scripts that include HTML and other markup,because it allows you to keep the markup relatively free of escape characters that would otherwise reduce the readability of it.


7undef


Undefines the value of EXPR,which must be an lvalue. Use only on ascalar value,an array (using@),a hash (using %),a subroutine(using &),or a typeglob (using*). Saying undef$hash{$key}will probably not do what you expect on most predefined variables orDBM list values,so don't do that; seedelete. Always returns theundefined value. You can omit the EXPR,in which case nothing isundefined,but you still get an undefined value that you could,forinstance,return from a subroutine,assign to a variable,or pass as aparameter. Examples:

 
 
  1. undef $foo;
  2. undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'};
  3. undef @ary;
  4. undef %hash;
  5. undef &mysub;
  6. undef *xyz; # destroys $xyz,@xyz,%xyz,&xyz,etc.
  7. return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it;
  8. select undef, undef, 0.25;
  9. ($a, $b, $c) = &foo; # Ignore third value returned

Note that this is a unary operator,not a list operator.


在许多编程语言中,都会有特殊的方法来表示“该字段没有值”。SQL,PHP Java 使用NULLPython 中是NoneRuby 中则是Nil

而在Perl的世界中,这个值称为undef

来看下细节。

哪里可以得到undef?

当你声明一个标量,却没有赋值时,它会被定义成undef

  
  
  1. my $x;

有些函数用返回 undef 来表示执行失败了,其它函数则会在没有可返回值时返回undef。

  
  
  1. my $x = do_something();

你可以使用 undef() 函数把一个变量重置为 undef:

  
  
  1. # some code
  2. undef $x;

甚至你也可以使用 undef() 的返回值来把一个变量设置为undef:

  
  
  1. $x = undef;

函数名后面的括号是可选的,所以我在这例子中省略了它们。

如你看到的这样,有很多方法可以把一个标量设置为undef。接下来的问题是:如果你使用这样一个变量会怎么样?

在此之前,先看一下其他的东西:

如何检查一个变量的值是否为undef?

如果给定的值不是undef,defined()函数会返回true 。如果给定值是undef则返回false 。

你也可以这么用:

  
  
  1. use strict;
  2. use warnings;
  3. use 5.010;
  4. ?
  5. my $x;
  6. ?
  7. # 这里的某些代码可能会给$x赋值
  8. ?
  9. if (defined $x) {
  10. say '$x is defined';
  11. } else {
  12. say '$x is undef';
  13. }

undef的真实值是什么?

因为 undef 表示缺失一个值,它仍是不可用的。除此之外,Perl还提供了两个可用的默认值。

如果你在数值操作中使用 undef,它效果上看起来和0一样。

如果它是用在字符串操作中,则基本等同于空字符串。

看下面的例子:

  
  
  1. use strict;
  2. use warnings;
  3. use 5.010;
  4. ?
  5. my $x;
  6. say $x + 4, ; # 4
  7. say 'Foo' . $x . 'Bar' ; # FooBar
  8. ?
  9. $x++;
  10. say $x; # 1

在上面的例子中,变量 $x (默认是 undef ),在加法运算中起的作用是0,在字符串连接过程中表现为空串,而在自增操作中又表现为0。

它也并不是完美的。如果你通过 use warnings 语句开启警告(推荐使用),那么你将在前两个操作中得到use of unitialized value 警告,但是自增操作却不会。

Use of uninitialized value $x in addition (+) at ... line 6.
Use of uninitialized value $x in concatenation (.) or string at ... line 7.

如果你现在不知道Perl的自增操作也没关系,后面我们会看到,它在处理计数操作的时候有多么方便。

当然,你可以通过给变量初始化成正确的数值(根据你的需要赋值0或空串)来避免警告,或者选择性的关闭警告。我们将在另外单独的文章中讨论这些。

8@INC:


@INC

The array @INC contains the list of places that thedoEXPR,require,oruse constructs look for their library files. Itinitially consists of the arguments to any-I command-lineswitches,followed by the default Perl library,probably/usr/local/lib/perl,followed by ".",to represent the currentdirectory. ("." will not be appended if taint checks are enabled,either by-T or by -t.) If you need to modify this at runtime,you should use theuselib pragma to get the machine-dependentlibrary properly loaded also:

 
 
  1. use lib '/mypath/libdir/';
  2. use SomeMod;

You can also insert hooks into the file inclusion system by putting Perlcode directly into@INC. Those hooks may be subroutine references,array references or blessed objects. Seerequire for details.


9 perl print 和printf 区别:

printf用于格式化输出

?

10如何去掉空格和换行:my $string= "Current configuration : 17448 bytes????????????????????????????? |? Current configuration : 17331 bytes ";$string =~ s/s+/ /gs;print "$stringn"

Prints:

Current configuration : 17448 bytes | Current configuration : 17331 bytes
?

This will trim whitespace from both sides.

from just the right:

$myString =~ s/^s*(.*?)s*$/$1/;$myString =~ s/s*$//;

$str=~s/^s+|s+$//g;$str=~s/^s+|s+$//g;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读