Perl lc Function

The lc function is used to convert all the characters of a string in lowercase and to return the new string.

Perl lc function (lc stands for lowercase) accepts as parameter an expression and returns a lowercase version of that expression.

We have two syntax forms for this function:

lc EXPR
lc
The lc function doesn’t change the content of a EXPR string variable, it merely returns a lowercase copy of the string. If the EXPR is omitted, the function is called against the special variable $_.

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

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

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

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

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my $str1 = " rose";
my $str2 = " ROSE";
if(lc $str1 eq lc $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 lowercase characters:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my @months = qw(January February March April May June);
map {$_ = lc($_)} @months;
 
print "@months\n";
To do this the map and lc 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