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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.