-1

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.

Brad Gilbert
  • 33,846
  • 11
  • 78
  • 129
VAR121
  • 512
  • 2
  • 5
  • 16
  • if a take a value(number) from user if 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 – VAR121 Sep 25 '12 at 19:59
  • 6
    Should have asked that! – ikegami Sep 25 '12 at 20:00

3 Answers3

8

[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 "".

ikegami
  • 367,544
  • 15
  • 269
  • 518
4

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.

Community
  • 1
  • 1
zellio
  • 31,308
  • 1
  • 42
  • 61
3

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

amon
  • 57,091
  • 2
  • 89
  • 149