-1

why this perl code increment $v string by 1

 use strict;
    use warnings;

   my $v='AAAAAYAQUypALsDz';

    print ++$v

while the below is not:

use strict;
use warnings;


my $v='AAAAAmGJoD1dlkkt';
    print ++$v

and i get Argument "AAAAAmGJoD1dlkkt" isn't numeric in preincrement (++)

any idea why this happens and how to increment such string by 1 using Perl?

2
  • 2
    "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" The value in $v doesn't match the pattern that activates the "magic" string increment. Commented Jul 17, 2019 at 2:45
  • Besides, you have a mix of lowercase and uppercase letters in your string, so it doesn't make sense to use ++; it couldn't possibly do what you want (whatever that is). Commented Jul 17, 2019 at 3:25

1 Answer 1

0

As ikegami mentioned, perl does not interpret the second string as a number. So you could do

use strict;
use warnings;

my $v='AAAAAmGJoD1dlkkt';
my $v = scalar $v;
print ++$v;

Now if you want to add "1" to the end of the string, you should this

$v .= '1';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.