Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: what is scalar?

by CheeseLord (Deacon)
on Jul 09, 2001 at 06:56 UTC ( [id://94894]=note: print w/replies, xml ) Need Help??


in reply to what is scalar?

Interesting question... I think I can answer it.

Basically, localtime is specially written such that calling it in scalar context (which is what scalar does) will return a string, rather than just a list converted to scalar (e.g. 9). This is done through using wantarray. Take this example:

sub cheese { my @cheese = qw(cheddar swiss); if (wantarray) { return @cheese } else { return $cheese[0] } }

Basically, wantarray will tell you if your subroutine was called in scalar or list context, as I understand it. It's used here to return at least some kind of cheese, so that if all the caller wants is some cheese, they'll get it.

It should also be noted that you can check to see if the sub was called in void context by using defined wantarray.

BTW, if you really wanted 9, you could try this code:

scalar (@_ = localtime(time))

Update: Or you could do like bwana147 suggested and assign to an empty list, preserving the contents of @_. That'd probably be better.

(I only hope not too many people think I'm obsessed w/ cheese now...)

His Royal Cheeziness

Replies are listed 'Best First'.
Re: Re: what is scalar?
by bwana147 (Pilgrim) on Jul 09, 2001 at 14:07 UTC

    You can also force list context without changing @_ by assigning to an empty list.

    scalar ( () = localtime(time) );
    The scalar value of a list assignement is the number of elements in the list on the right side of the assignment. This yields the number of elements returned by localtime (not the number of elements in the empty list, that would be dull).

    --bwana147

Re: Re: what is scalar?
by Seumas (Curate) on Jul 09, 2001 at 07:21 UTC
    Cheese obsession? No, do roll with it!

    Instead of the historical Fred, Barney, Adam, Eve, Alice and Bob, the standard will become Munster, Cheddar, Gouda, Brie, Parmesan, Ricotta, Swiss, Monteray Jack, Mozzarella, Derby, Colby, Blue, Feta, Cheshire and Provolone!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-16 20:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found