perl function scalar
The scalar
function in Perl is used to return the number of items in an array or the number of keys in a hash.
Here's an example of using scalar
with an array:
my @array = (1, 2, 3, 4, 5); my $count = scalar @array; print "$count\n"; # prints 5
In this example, the scalar
function is used to return the number of items in the array @array
. The result is assigned to the variable $count
, which is then printed.
Here's an example of using scalar
with a hash:
my %hash = ('apple' => 1, 'banana' => 2, 'orange' => 3); my $count = scalar keys %hash; print "$count\n"; # prints 3
In this example, the scalar
function is used to return the number of keys in the hash %hash
. The keys
function is used to extract the keys from %hash
, and the scalar
function is used to count the number of keys. The result is assigned to the variable $count
, which is then printed.
Note that the scalar
function can also be used to convert a list to a scalar value. When used in scalar context, a list evaluates to its length. Here's an example:
my @array = (1, 2, 3, 4, 5); my $count = scalar(@array, "foo", "bar"); print "$count\n"; # prints 7
In this example, the scalar
function is used to convert the list (1, 2, 3, 4, 5, "foo", "bar")
to a scalar value, which is the length of the list. The result is assigned to the variable $count
, which is then printed.