Perl | scalar keyword

scalar keyword in Perl is used to convert the expression to scalar context. This is a forceful evaluation of expression to scalar context even if it works well in list context.

Syntax: scalar expr

Returns: a scalar value

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Defining Arrays 
@array1 = ("Geeks", "For", "Geeks");
@array2 = (1, 1, 0, 0, 9, 6);
  
# Concatenation of both arrays 
@array3 = (@array1, @array2);
  
# Printing the Concatenated Array 
# in List form
print "Array in List form: @array3\n";
  
# Conversion of Arrays to scalar context
@array3 = (scalar(@array1), scalar(@array2));
  
# Conversion to scalar returns
# the number of elements in the array
print "Array in scalar form: @array3\n";

chevron_right


Output:

Array in List form: Geeks For Geeks 1 1 0 0 9 6
Array in scalar form: 3 6

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Defining Arrays 
@array1 = ("Welcome", "To", "Geeks");
@array2 = (1, 1, 0, 0, 9, 6);
  
# Concatnation of both arrays 
@array3 = ( @array1, @array2 );
  
# Printing the Concatenated Array 
print "Concatenation of Arrays: @array3\n";
  
# Conversion of Arrays to scalar context to
# Evaluate Difference between size of arrays
@array3 = (scalar(@array2) - scalar(@array1));
  
# Printing the size Difference
print "Difference in number of elements: @array3\n";

chevron_right


Output:

Concatenation of Arrays: Welcome To Geeks 1 1 0 0 9 6
Difference in number of elements: 3


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.