Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help on Return statement

Status
Not open for further replies.

Tve

Programmer
May 22, 2000
166
FR
I have used the following syntax that I found in the "Perl CD BookShelf" by O'Reilly (by the way, this CD is really fantastic).

Unfortunatly, I don't understand the return statement...
Can somebody explain this?

sub trim {
my @out = @_;
for (@out) {
s/^\s+//;
s/\s+$//;
}
return wantarray ? @out : $out[0];
}

Thanks,

Thierry
 
from O'Reilly's "Programming Perl",.....

quote...
Trinary ?: is the conditional operator, just as in C. It words as:

TEST_EXPR ? IF_TRUE_EXPRESS : IF_FALSE_EXPR

much like an if-then-else, except that it can safely be embedded within other operations and functions. If the TEST_EXPR is true, only the IF_TRUE_EXPR is evaluated, and value of the expression becomres the value of th entire expression. Otherwise, only the IF_FALSE_EXPR is evaluated, and it value becomes the value of the entire expression.
.....end quote.

So, if 'wantarray' is a string or a function or variable that evaluates true, then the RETURN spits out the entire array, @out. If 'wantarray' is a function or variable that evaluates to false, then the RETURN spits out the first element of the array, @out.

'hope this helps.....




keep the rudder amid ship and beware the odd typo
 
Also, remember that, if wantarray does not exist, it evaluates to false. If it is a string or it is a number !=0, it will evaluate to true.
Sincerely,

Tom Anderson
CEO, Order amid Chaos, Inc.
 
why wouldn't wantarray exist? wantarray is a perl function. a really cool one at that. this line is saying that if you call the subroutine in a scalar context, it provides a scalar return, otherwise it returns an array. adam@aauser.com
 
I was talking about a more generic instance of the ? statment. Actually, I had no idea what the wantarray function did. Is it built in?

If it weren't built in, then it might not exist, and if it did not exist, it would evaluate as false. That's all I was saying.

Sounds like a cool function though. I'll have to remember that.
Sincerely,

Tom Anderson
CEO, Order amid Chaos, Inc.
 
it is built in, at least in 5.6, i'm not sure about previous versions of perl, because i dont have a previous version to test with. adam@aauser.com
 
it's a builtin and, lacking an argument, it looks at $_
Mike
michael.j.lacey@ntlworld.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top