Question

Preceding a number with escape character '\' produces garbage value Ex:

$a = \12;
print $a;

This code gives below output

SCALAR(0x2001ea8)

and the output changes when I again execute the program.

If I take a value(number) from user when the user gives any input starting with zero, I dont want it to interpret as octal number. So I wanted to escape zero if the number starts with zero.

Was it helpful?

Solution

[In a comment, the OP explained he wants numbers input by the user to be treated as decimal even if they have leading zeroes.]

In numerical literals (code that produces a number), a leading zero tells Perl that the number is in octal.

$ perl -E'say 045'
37

But that does not apply to numification (converting a string to a number).

# "045" is the same as reading 045 from handle or @ARGV.
$ perl -E'say 0+"045"'
45

So you don't have to do anything special. A 045 input by the user means forty-five (not thirty-seven) if you use it as a number.

If for some reason you did need to get rid of the leading zero, you could use

$var =~ s/^0+(?!\z)//;

The (?!\z) makes sure "0" doesn't become "".

OTHER TIPS

It's not a garbage value. You are getting what Perl prints out when it prints a reference.

TYPE(ADDRESS)

It's expected functionality. If you want a \ in your string you'll need to escape it.

$str = "\\12";

Or as Ted Hopp pointed out in the comments with a string literal

$str = '\12';

See the Perl doc for more information.

In Perl, \ is the reference operator. It is analogous to C's & (address-of)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top