Grep function Introduction

Source: Internet
Author: User
Tags glob
Grep function introduction-general Linux technology-Linux programming and kernel information. The following is a detailed description. Grep function Introduction


[Table = 98%] [tr] [td = 100%,] [/td] [/tr] [/table]
Grep Function
(If you are a beginner in Perl, you can skip the following two sections and go directly to the Grep vs. loops sample section. Rest assured that you will see it later)


grep BLOCK LIST
grep EXPR, LIST

The grep function evaluates BLOCK or EXPR with the element in the LIST, and sets the local variable $ _ as the element in the LIST currently used. A block is one or more Perl statements separated by curly brackets, while a List is an ordered List. EXPR is an expression composed of one or more variables, operators, characters, functions, and subprograms. Grep evaluates BLOCK or EXPR, and adds the element with the % {color: red} true % To The Grep return list. If a BLOCK is composed of multiple statements, Grep evaluates the last statement in the BLOCK. A list can be a LIST or an array. In a scalar context, grep returns the number of true Elements measured by BLOCK or EXPR. Avoid modifying $ _ in the BLOCK or expr block because the value of the element in the LIST is modified accordingly. At the same time, avoid using the LIST returned by grep as the left value, because it also modifies the elements in the LIST. (The left variable is a variable on the left of the value assignment expression ). Some Perl hackers may exploit this so-called "feature", but I suggest you do not use this messy programming style.
Grep and loop
In this example, the myfile file contains terriosm and nuclear rows (Case Insensitive ).


Open FILE" Print grep/terrorism | nuclear/I, ;

This code consumes a lot of memory when the file is large. Because grep treats its second parameter as a list context, the <> operator returns the entire file. More effective code should be written as follows:


While ($ line = ){
If ($ line = ~ /Terrorism | nuclear/I) {print $ line}
}
Through the above, we can see that the cycle can complete all the work that grep can do. So why do we need to use grep? The intuitive answer is that grep is more like Perl, while loops is C. A better answer is: first, grep intuitively tells the reader that the operation being performed is to select the desired value from a string of values. Secondly, grep is more concise than loop. (In software engineering, grep is more cohesive than loops ). Basically, if you are not familiar with Perl, you can use loops. Otherwise, you should use powerful tools like grep. Calculates the number of elements matching a given pattern in the array.
In a scalar context, grep returns the number of matched elements.
$ Num_apple = grep/^ apple $/I, @ fruits;
^ The combination of the $ identifier specifies that only the elements starting with apple and ending with apple are matched. Here, grep matches apple, but pineapple does not. Different elements in the output list
@ Unique = grep {++ $ count {$ _} <2}
Qw (a B a c d e f g f h );
Print "@ unique \ n ";

Output result: a B c d e f g h $ count {$ _} is an element in the Perl hash, is a key-Value Pair (the hash in Perl is related to the hash table in computer science, but not exactly the same) here the count hash key is the values in the input list, the value corresponding to each key is whether the key makes the BLOCK valuation true. When a value appears for the first time, the BLOCK value is estimated to be true (because it is smaller than 2). When the value appears again, It is estimated to be false (because it is equal to or greater than 2 ). Retrieve the value that appears twice in the list


@ Crops = qw (wheat corn barley rice corn soybean hay
Alfalfa rice hay beets corn hay );
@ Duplicates = grep {$ count {$ _} = 2}
Grep {++ $ count {$ _}> 1} @ crops;
Print "@ duplicates \ n ";
Before the first list element of grep is passed to the BLOCK or expr block, the second parameter is treated as the list context. This means that the second grep will completely read the count hash before grep on the left begins to evaluate the BLOCK. List text files in the current directory
@ Files = grep {-f and-T} glob '*.*';
Print "@ files \ n ";
The glob function is independent of the operating system. It matches the file extension like a Unix shell. A single "*" indicates matching files that do not start with "." in the current directory. "*" indicates matching all files starting with "." in the current directory. The-f and-T file test characters are used to test both pure files and text files. If yes, true is returned. Testing with-f and-T is more effective than testing with-T alone, because if a file does not pass the-f test, the-T test, which is more time-consuming than-f, will not be performed. Select non-repeating elements from the array
@ Array = qw (To be or not to be that is the question );
Print "@ array \ n ";
@ Found_words =
Grep {$ _ = ~ /B | o/I and ++ $ counts {$ _} <2 ;}@ array;
Print "@ found_words \ n ";

Output result:
To be or not to be that is the question
To be or not to question logical expression $ _ = ~ /B | o/I matching elements that contain B or o (case-insensitive ). In this example, placing the matching operation before accumulation is more effective than doing the opposite. For example, if the expression on the left is false, the expression on the right is not calculated.
Select the elements whose abscissa is greater than the ordinate value in the two-dimensional coordinate array.
# An array of references to anonymous arrays
@ Data_points = ([5, 12], [20,-3],
[2, 2], [13, 20]);
@ Y_gt_x = grep {$ _-> [0] <$ _-> [1]} @ data_points;
Foreach $ xy (@ y_gt_x) {print "$ xy-> [0], $ xy-> [1] \ n "}

Output result:
5, 12
13, 20 Search for restaurants in a simple database
In this example, the database implementation method is not used in actual applications, but it shows that when you use the grep function, as long as you have enough memory, there is basically no limit on the complexity of BLOCK blocks.

# @ Database is array of references to anonymous hashes
@ Database = (
{Name => "Wild Ginger ",
City => "Seattle ",
Cuisine => "Asian Thai Chinese Korean Japanese ",
Expense => 4,
Music => "\ 0 ",
Meals => "lunch dinner ",
View => "\ 0 ",
Smoking => "\ 0 ",
Parking => "validated ",
Rating => 4,
Payment => "mc visa amex ",
},
# {...}, Etc.
);

Sub findRestaurants {
My ($ database, $ query) = @_;
Return grep {
$ Query-> {city }?
Lc ($ query-> {city}) eq lc ($ _-> {city}): 1
And $ query-> {cuisine }?
$ _-> {Cuisine} = ~ /$ Query-> {cuisine}/I: 1
And $ query-> {min_expense }?
$ _-> {Expense }>=$ query-> {min_expense}: 1
And $ query-> {max_expense }?
$ _-> {Expense} <= $ query-> {max_expense}: 1
And $ query-> {music }? $ _-> {Music}: 1
And $ query-> {music_type }?
$ _-> {Music} = ~ /$ Query-> {music_type}/I: 1
And $ query-> {meals }?
$ _-> {Meals} = ~ /$ Query-> {meals}/I: 1
And $ query-> {view }? $ _-> {View}: 1
And $ query-> {smoking }? $ _-> {Smoking}: 1
And $ query-> {parking }? $ _-> {Parking}: 1
And $ query-> {min_rating }?
$ _-> {Rating }>=$ query-> {min_rating}: 1
And $ query-> {max_rating }?
$ _-> {Rating} <= $ query-> {max_rating}: 1
And $ query-> {payment }?
$ _-> {Payment} = ~ /$ Query-> {payment}/I: 1
} @ $ Database;
}

% Query = (city => 'seattle ', cuisine => 'Asian | thai ');
@ Mongoants = findRestaurants (\ @ database, \ % query );
Print "$ your ants [0]-> {name} \ n ";

Output result: Wild Ginger
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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.