Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: Restrict a match within a string

by Marshall (Canon)
on Jan 28, 2017 at 21:25 UTC ( [id://1180540]=note: print w/replies, xml ) Need Help??


in reply to Re: Restrict a match within a string
in thread Restrict a match within a string

Hi SavannahLion?

I'm not sure if this anon Monk is you or somebody else?

You already understand some key fundamentals of NetWallah's code, but you just don't know what you know. An attempt to clarify.

In your code, my ($sb) = $sa =~ m/\((.+?)\)/; You knew that parenthesis were required for ($sb). That puts $sb into a list context. This assigns the first element of the list on the right to $sb. That is the "contents" of the first and only match. If you do not have the paren's, $sb will wind up being "1", the number of matches. I think you figured that part out on your own.

You could have written, my $sb = ($sa =~ m/\((.+?)\)/)[0]; that takes a list slice of the stuff on the right and assigns the zeroth element of that list to the simple scalar $sb on the left. This is functionally the same as your code.

So, my $sab = $sa =~ m/\((.+?)\)/)[0] is just exactly the same as your: my ($sb) = $sa =~ m/\((.+?)\)/;. There is not an explictly named $sb variable, but it is still there, just with some computer generated name that you don't know.

The next part, =~/(\w+)/g is the same as if you had written my (@ab) = $sb =~/(\w+)/g. You used a split instead of the match global regex, my @ab = split(',',$sb); but these statements amount to about the same thing. In NetWallah's version there is not an explictly named array, @ab, but it is there under some computer generated name that you don't know. That array is fed into the join.

So, now I come to my point...

Your code and the more cryptic looking code are about the same and will have similar performance. I actually think your code as written is fine. It takes a few more lines, but it is easy to understand. Giving $sb and @ab explict names doesn't really cost anything. With Perl, fewer lines of code does not necessarily mean "faster" code. I've seen some devilishly tricky lines of code that actually run much slower that a more obvious approach would. My recommendation is to go for clarity as the first priority. Will you or somebody else understand the code a couple of years from now?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1180540]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-24 00:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found