Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through characters in Perl

Tags:

for-loop

perl

I'm having quite a difficulty, figuring out some strange behavior when looping through symbols in Perl, using the for loop. This code snippet works just as expected:

for (my $file = 'a'; $file le 'h'; $file++) {
    print $file;
}

Output: abcdefgh

But when I try the loop through the symbols backward, like this:

for (my $file = 'h'; $file ge 'a'; $file--) { 
    print $file;
}

gives me the following as a result.

Output: h

Maybe the decrement operator doesn't behave as I think it does when symbols are involved?

Does anybody have any ideas on the matter? I'd really appreciate your help!

Regards,

Tommy

like image 203
Tomislav Dyulgerov Avatar asked Jan 31 '12 20:01

Tomislav Dyulgerov


People also ask

How do I iterate through a string in Perl?

The foreach keyword is probably the easiest and most often used looping construct in Perl. Use it for looping through the items in an array. Here we're creating an array and initializing it with three strings, then displaying the strings by looping through the array with foreach and printing the strings with print.

How do I find the first character of a string in Perl?

You can access the first characters of a string with substr(). To get the first character, for example, start at position 0 and grab the string of length 1.

How do you find the length of a string in Perl?

length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Return: Returns the size of the string.


1 Answers

The auto-decrement operator is not magical, as per perlop

You can do something like this though:

for my $file (reverse 'a' .. 'h') { 
    print $file;
}
like image 116
Eric Strom Avatar answered Oct 27 '22 14:10

Eric Strom