perl 数组grep
The Perl grep() function is a filter that runs a regular expression on each element of an array and returns only the elements that evaluate as true. Using regular expressions can be extremely powerful and complex. The grep() functions uses the syntax @List = grep(Expression, @array).
Perl grep()函数是一个过滤器,它在数组的每个元素上运行正则表达式,并且仅返回评估为true的元素。 使用正则表达式可能非常强大和复杂。 grep()函数使用语法@List = grep(Expression,@array)。
使用Grep()函数返回真表达式 ( Using Grep() Function to Return True Expressions )
@myNames = ('Jacob', 'Michael', 'Joshua', 'Mathew', 'Alexander', &
@grepNames = grep(/^A
Think of the @myNames array as a row of numbered boxes, going from left to right and numbered starting with a zero. The grep() function goes through each of the elements (boxes) in the array and compares their contents to the regular expression. If the result is true, the contents are then added to the new @grepNames array.
将@myNames数组视为一排带编号的框,从左到右并从零开始编号。 grep()函数遍历数组中的每个元素(框),并将其内容与正则表达式进行比较。 如果结果为true ,则将内容添加到新的@grepNames数组中。
In the above example, the regular expression /^A/ is looking for any value that starts with a capital A. After sifting through the contents of the @myNames array, the value of @grepNames becomes ('Alexander', 'Andrew'), the only two elements that start with a capital A.
在上面的示例中,正则表达式/ ^ A /正在查找以大写字母A开头的任何值。在@myNames数组的内容中进行筛选后,@ grepNames的值变为('Alexander','Andrew') ,只有两个以大写字母A开头的元素。
反转Grep()函数中的表达式 ( Reversing the Expression in a Grep() Function )
One quick way to make this particular function more powerful is to reverse the regular expression with the NOT operator. The regular expression then looks for elements that evaluate to false and moves them into the new array.
使此特定功能更强大的一种快速方法是使用NOT运算符反转正则表达式。 然后,正则表达式将查找结果为false的元素,并将其移动到新数组中。
@myNames = ('Jacob', 'Michael', 'Joshua', 'Mathew', 'Alexander', &
@grepNames = grep(!/^A
In the above example, the regular expression is looking for any value that does not start with a capital A. After sifting through the contents of the @myNames array, the value of @grepNames becomes ('Jacob', 'Michael', 'Joshua', 'Matthew').
在上面的示例中,正则表达式正在寻找不以大写字母A开头的任何值。在@myNames数组的内容中进行筛选后,@ grepNames的值变为('Jacob','Michael','Joshua ', '马修')。
关于Perl ( About Perl )
Perl is an adaptable programming language frequently used to develop web applications. Perl is an interpreted, not compiled, language, so its programs take up more CPU time than a compiled language—a problem that becomes less important as the speed of processors increases. However, writing in Perl is faster than writing in a compiled language, so the time you save is yours.
Perl是一种经常用于开发Web应用程序的适应性编程语言。 Perl是一种解释性而非编译语言,因此它的程序比编译语言占用更多的CPU时间-随着处理器速度的提高,此问题变得不那么重要了。 但是,用Perl编写要比用编译语言编写要快,因此节省的时间就是您自己的。
翻译自: https://www.thoughtco.com/perl-array-grep-function-quick-tutorial-2641158
perl 数组grep