$_ and @_ in the Perl language

Source: Internet
Author: User

Perl-$_ and @_ Perl ' a great language for special Variables-variables this are set up without the programmer has t o intervene and providing information ranging from the number of lines read to the current input file ($.) through the C Urrent process ID ($$) and the operating system ($^O). Other special variables effect certain operations are performed ($| controlling output buffering/flushing for Examp Le), or are fundamental in the operation of the certain facilities-no more so than $_ and @_.

Lets clear a misconception. $_ and @_ are different variables. In Perl, you can have a list and a scalar of the same name, and they refer to unrelated pieces of memory.

$_ is known as the ' default input and pattern matching spaces '. In other words, if you read in from a file handle at the top of a while loop, or run a foreach loop and don ' t name a loop Variable, $_ is set up for you. Then any regular expression matches, chops (with LCS and many more) without a parameter, and even prints assume your want to Work on $_. Thus:
while ($line = <FH>) {
if ($line =~/perl/) {
Print FHO $line;
}
Print UC $line;
}

Shortens to:
while (<FH>) {
/perl/and
Print FHO;
Print UC;
}

@_ is the list of incoming parameters to a sub. So if you are write a sub, you are refer to the the ' the ' the ' the ' parameter in it as $_[0], the second parameter as $_[1] and. And you can refer to $_# as the index number of the last parameter:
Sub Demo {
Print "Called with", $ #_ +1, "params/n";
Print "A param was $_[0]/n";

Note that the Chinese module adds in the ability to refer to the special variables from other longer, but easier to remember , names such as @ARG for @_ and $PID for $$. But use 中文版; Can have a detrimental performance effect if you ' re matching regular the expressions against long incoming strings.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: