Grep could have been called "filter". But it is: "get regular expression".
Use grep when you think about getting a subset of an array.
use strict;
use warnings;
my @x = ("aaBxyz", "..Bxys", "bbxyzzy", "xxAx");
# for each element in the array @x,
# pass that element to the array @result if
# if the 3rd character is either A or B
# followed by at least one character.
my @result = grep {/^..(A|B)./}@x;
print "$_\n" for @result;
=prints
aaBxyz
..Bxys
xxAx
=cut
Yes, in this case $1 will be either A or B if the regex is True.
I can show that, but I don't want to confuse you.
Here $1 is not relevant.
Ok, on second thought, here we go...
#ok, with a weird example of $1
@result = grep{ print "$1 $_\n" if /^..(A|B)./;
/^..(A|B)./}@x;
=prints
B aaBxyz
B ..Bxys
A xxAx
=cut
@result is the same as above
# grep {} executes the code within the brackets and passes the input
# to @result depending upon the true/false value of the last statement
+.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.