one extracts the value of $1 from the regex m/\s*(\S+)\s*(\S+)\s*(\S+)\s*(\S+)\s*/ and the other extracts the value of $2. So I thought why not merge these into one function and pass the column number which I want to extract as a parameter?
You're thinking along the right lines. My first suggestion would be to do just what you said: combine it into one function...
sub nthword { my ($texttomatch, $fieldnum) = @_; ($texttomatch =~ m/\s*(\S+)\s*(\S+)\s*(\S+)\s*(\S+)\s*/)[$fieldnum]; }
As another poster points out, this will be indexed from zero, so if you want it indexed from one use $fieldnum+1 in the brackets.
My second thought is that the regular expression is very regular. If this is really the regex you're working with, you might be able to use split to further simplify your code.
sub nthword { my ($texttomatch, $fieldnum) = @_; (split /\s+|^/, $texttomatch)[$fieldnum]; }
This is now simple enough it could almost be inlined. It is not exactly the same, but if your data is the way I guess it might be it will be equivalent. (Where you run into differences is if your original regex is sometimes running off the end of the string, backtracking, and matching the last instances of \s* against the null string in order to get a match. But I'm guessing that if it does that it's not what you intended anyway, so my version should be fine.)
$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/
In reply to Re: How to remove the $1 hard coding
by jonadab
in thread How to remove the $1 hard coding
by abhishes
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |