Perl uc Function

The uc function converts all the characters of a string in uppercase and returns the new string.

The uc function (which stands for uppercase) is meant to return an uppercase version of a string expression.

There are two syntax forms for the uc function:

uc EXPR
uc
 
Please note that the uc function doesn’t alter the string variable content, but it returns an uppercase copy of the string. If you omit the EXPR parameter, the uc function will use the content of the special variable $_.

The following example shows you how to convert a string in lowercase, using the Perl uc function:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
# initialize some string variable
my $str = "What is Perl Language for";
uc($str);
print $str, "\n";
# displays: What is Perl Language for
 
$str = uc($str);
print $str, "\n";
# displays: WHAT IS PERL LANGUAGE FOR
The Perl uc function doesn’t change the content of a EXPR string variable, it merely returns an uppercase copy of the string.

In our example, the first call of the uc function converts $str to uppercase, but without an assignment the conversion was lost. The next lines of the code show you how to do it.

The next code snippet compares two strings case insensitive, by calling the uc function for both of them:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my $str1 = " rose";
my $str2 = " ROSE";
if(uc $str1 eq uc $str2 ) {
  print "The two strings are equal\n";
}
# it expects to print: The two strings are equal

The following example will show you how to convert all the array elements in uppercase characters:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my @months = qw(January February March April May June);
map {$_ = uc($_)} @months;
 
print "@months\n";
To do this the map and uc functions are used. The map function will execute the block for each element of the @months array. At each iteration step, the elements of the array are assigned in turned to $_ and then are converted in uppercase.
 
Within a map or a foreach block the placeholder variable (in our case $_) is an alias for the array element and that means you can easily modify it in place.

The output:

JANUARY FEBRUARY MARCH APRIL MAY JUNE