#!\usr\bin\perl -w
for($_="head";s/(.)//;){
print"now head is $_.\n";
}
| [reply] [Watch: Dir/Any] [d/l] |
...tell me why the two can come to the same result...
#!\usr\bin\perl -w
for($_="head";s/(.)//;){
print"now head is $_.\n";
}
#!\usr\bin\perl -w
for($_="head";s/.//;){
print"now head is $_.\n";
}
The only difference between your (updated) two samples, is that in the first you have capturing brackets. These will cause the matched character to be copied into $1. But then you do nothing with $1, so otherwise both samples are the same:
Match a (the first) character in $_, and then delete it; print out the contents of $_; repeat until no match occurs, which will be when $_ is empty.
What difference were you expecting?
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
| [reply] [Watch: Dir/Any] [d/l] |
Thank you for your explainationS to me,I know the "()" has memory function, also I know that the function of ".", I enconter
#!\usr\bin\perl -w
for($_="head";s/(.)//;){
print"now head is $_.\n";
}
in the book learning perl, I am confused why not just "."
So I ask this question.
Janitored by Arunbear - added code tags, as per Monastery guidelines
| [reply] [Watch: Dir/Any] [d/l] |
They give the same output because they are still technically the same.
The only difference is the parenthesis in the regex around the "any single character" ( or "." ).
The role of parenthesis here is to group parts of the regex together and to create back references ($1, $2 etc). See the perlre documentation for full details on what it does.
In this particular case it's making no difference to the operation of the regex in question.
--- Jay
All code is untested unless otherwise stated.
All opinions expressed are my own and are intended as guidance, not gospel; please treat what I say as such and as Abigail said Think for yourself.
If in doubt ask.
| [reply] [Watch: Dir/Any] [d/l] |