Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl go up a character?

Tags:

perl

In Perl, lets say I have the letter A in variable called $character, and I want it to go up to B, how would I do this? The $character can also be numbers (0-8) and I want the method work on both of them? (Something like binary shift, but not exactly sure if it is something like that). Thanks in advance.

like image 435
Grigor Avatar asked Nov 30 '22 23:11

Grigor


2 Answers

Simple increment should do what you want:

my $character = "A";
$character++;

from perl-doc:

The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern /^a-zA-Z*0-9*\z/ , the increment is done as a string, preserving each character within its range, with carry

like image 21
perreal Avatar answered Dec 03 '22 13:12

perreal


The increment operator may be what you want. However, do make sure that you want the boundary behavior. For instance:

my $character = 'Z';
print ++$character;

Produces:

AA

This is the "with carry" from http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement.

like image 119
rynemccall Avatar answered Dec 03 '22 14:12

rynemccall