Reputation: 5927
Array
my @ar = qw(one two);
print ~@ar,"\n";
#output 18446744073709551613
Scalar (Result is very interesting )
my $ar = "qw(onetwo)";
print ~$ar
#Output Please refer the screen shot.
My question is what ~
does?
For array it is giving the some numbers.
For scalar it is giving the some other characters, we I copied the character from terminal and pasted in gedit
, the result is after the long spaces characters printed with revers order. I can't delete the characters from last. If I'm trying to delete the spaces,characters are delete one by one(left to right). I can't understand what is going here.?
Upvotes: 1
Views: 143
Reputation: 33618
Unary ~
performs bitwise negation. Numbers are first converted to integers by discarding the fractional part, then each bit in the binary representation is flipped. So on a 64-bit system, you'll get:
$ perl -e 'printf "%x\n", ~0'
ffffffffffffffff
Double negation can be used to convert non-negative numbers to integers in a terse but unreadable way:
$ perl -le 'print ~~1.8'
1
Evaluated in scalar context, an array yields the number of elements, so for a two-element array, ~@a
is equivalent to ~2
.
When operating on strings, each bit in the binary representation of the string is flipped:
$ perl -le 'print unpack("B*", "A"), "\n", unpack("B*", ~"A")'
01000001
10111110
$ perl -le 'print unpack("H*", "onetwo"), "\n", unpack("H*", ~"onetwo")'
6f6e6574776f
90919a8b8890
6f
is the hex ASCII code for o
and 90
is the negated hex value. Since the MSB of each byte is flipped, you typically get garbage when printing the bitwise negation of a string.
Upvotes: 6
Reputation: 5720
From the docs:
Symbolic Unary Operators
[...]
Unary "~" performs bitwise negation, that is, 1's complement. For example, 0666 & ~027 is 0640.
[...]
Albeit it looks different, I assume ~@ar
does a bitwise negation of the number of elements in @ar
:
print ~2, "\n";
18446744073709551613
Upvotes: 4
Reputation: 402
Taken from perldoc manpage
Unary "
~
" performs bitwise negation, that is, 1's complement. For example, 0666 & ~027 is 0640.
However, the ~
operator has a bunch of other functions as well, for example the =~
operator is for applying a regular expression to a scalar.
In general, working with operators is a pretty messy ordeal, I suggest you consult the linked manpage if you have a question about them.
Upvotes: 1