Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: How does this code work? (from "Perl is Unix")

by bobf (Monsignor)
on Nov 06, 2009 at 06:00 UTC ( [id://805399]=note: print w/replies, xml ) Need Help??


in reply to How does this code work? (from "Perl is Unix")

I'll take the first one, but I haven't played with forks so I'll leave that to wiser monks.

s/\A\s+//, s/\s+\z//
You are correct that this code is stripping white space. More precisely, it is stripping leading and trailing white space. In fact, this task is performed so often there is a snippet in perlfaq4. If you are wondering about the use of \A and \z, see perlre:
The \A and \Z are just like "^" and "$", except that they won't match multiple times when the /m modifier is used, while "^" and "$" will match at every internal line boundary. To match the actual end of the string and not ignore an optional trailing newline, use \z.

The other bit:

for my @r = @_;
does a couple of things. The for causes the preceding expression (regexen) to be executed for each of the items in the following list (the array @r). The @r = @_ makes a copy of the parameters passed to the subroutine (in @_, see perlvar) before they are used. This is important because the values in @_ are aliases to the original values (in the calling code, see perlsub) and if a copy was not made the original values would be modified. You can test this pretty easily - just change the code to use @_ directly and see what happens to the original values

Update: There are a couple of other things worth mentioning. The way the for loop is constructed, the default variable $_ is used (see perlvar), which aliases the elements in @r. Second, the final line, which contains a solitary @r, is a shorthand way of specifying the return value of the routine (remember, the elements of @r were changed via aliasing in the for loop). See perlsub:

If no return is found and if the last statement is an expression, its value is returned.
I won't get into how the value of the expression is determined as it is context dependent and can be tricky to understand.

Replies are listed 'Best First'.
Re^2: How does this code work? (from "Perl is Unix")
by Anonymous Monk on Nov 06, 2009 at 06:13 UTC

    Oh! I see now. This:

    s/\A\s+//, s/\s+\z// for my @r = @_;

    is the same as

    my @r = @_; s/\A\s+//, s/\s+\z// for @r;

    Thanks!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-23 07:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found