Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Puzzled over 'my'

by myomancer (Novice)
on Oct 23, 2003 at 12:42 UTC ( #301561=perlquestion: print w/ replies, xml ) Need Help??
myomancer has asked for the wisdom of the Perl Monks concerning the following question:

I was trying to use grep in a scalar context, and thought this would work:
my($ok) = grep {/Some String/} @anArray;
But this just returned "Some String" rather than a number. If I remove 'my', the code works as I expected. This has upset my mental picture of what 'my' actually does. Please can anybody point me at a good resource to explain the subtleties if 'my'? Many thanks, Myomancer

Comment on Puzzled over 'my'
Download Code
Re: Puzzled over 'my'
by shenme (Priest) on Oct 23, 2003 at 12:50 UTC
    Change it to
    my $ok = grep {/Some String/} @anArray;
    and you'll go back to scalar context.   Using the parentheses forced the matches into array context.
Re: Puzzled over 'my'
by Anonymous Monk on Oct 23, 2003 at 12:53 UTC
    This is list context.

    my($ok) = grep {/Some String/} @anArray;

    This is scalar context

    my $ok = grep {/Some String/} @anArray;
Re: Puzzled over 'my'
by tadman (Prior) on Oct 23, 2003 at 20:47 UTC
    You must've not only removed the my, but the brackets as well. It was the brackets, mind you, that are the key here.

    Including brackets means that you're assigning a list to a list, in this case, the result of the grep operation into a list containing the variable $ok. Thus, the first thing grepped goes into the first variable, and you get "Some String".

    If you want to know how many things you got, you need to force a list to scalar conversion. That might sound fancy, but it's just a way of saying you want to assign the list directly to the variable instead of to a list of variables. No brackets. If you're a bit fuzzy, here's some examples;
    my @list = ("A","B","C"); my ($var) = @list; # $var becomes "A" my $var = @list; # $var becomes 3 my ($var) = scalar(@list); # $var becomes 3 my $var = scalar(@list); # $var becomes 3 (same idea)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://301561]
Approved by phydeauxarff
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (11)
As of 2014-09-01 08:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (299 votes), past polls