Perl print function side effect

I am wondering why / how printin Perl can have a side effect.

use Scalar::Util qw/looks_like_number/; 

my @A = (5, '2', 'aaa', 1, 'aab'); 

my @a = map { looks_like_number($_) } @A; 
print "1) @a\n";
# prints "4352 1 0 4352 0"

print "A print with a side-effect: @A\n";

@a = map { looks_like_number($_) } @A; 
print "2) @a\n";
# prints "1 1 0 1 0"

This example looks_like_numberreturns 4352 1 0 4352 0before printing and 1 1 0 1 0after printing. A.

What is doing printfor these values ​​to influence how they are interpreted looks_like_number?

+4
source share
1 answer

When interpolating or concatenating a numeric value, you must create a string version. This string is stored inside the scalar (in addition to the numeric value) for later use, and this may affect what value looks_like_numberreturns.


, Devel::Peek [1].

use Devel::Peek qw( Dump );
my @A = (5, '2', 'aaa');
Dump($_) for @A;  # Or: Dump(\@A);
print "@A\n";
Dump($_) for @A;

Perl 5.20 : ( )

Before                             After
===============================    ===============================
SV = IV(0x4532a78) at 0x4532a88    SV = PVIV(0x45563a0) at 0x4532a88
  REFCNT = 2                         REFCNT = 2
  FLAGS = (IOK,pIOK)                 FLAGS = (IOK,POK,pIOK,pPOK)
  IV = 5                             IV = 5
                                     PV = 0x454a870 "5"\0
                                     CUR = 1
                                     LEN = 10

SV = PV(0x45336a0) at 0x4532c08    SV = PV(0x45336a0) at 0x4532c08
  REFCNT = 2                         REFCNT = 2
  FLAGS = (POK,IsCOW,pPOK)           FLAGS = (POK,IsCOW,pPOK)
  PV = 0x455cf00 "2"\0               PV = 0x455cf00 "2"\0
  CUR = 1                            CUR = 1
  LEN = 10                           LEN = 10
  COW_REFCNT = 1                     COW_REFCNT = 1

SV = PV(0x4533720) at 0x4550b90    SV = PV(0x4533720) at 0x4550b90
  REFCNT = 2                         REFCNT = 2
  FLAGS = (POK,IsCOW,pPOK)           FLAGS = (POK,IsCOW,pPOK)
  PV = 0x455f210 "aaa"\0             PV = 0x455f210 "aaa"\0
  CUR = 3                            CUR = 3
  LEN = 10                           LEN = 10
  COW_REFCNT = 1                     COW_REFCNT = 1

FLAGS. ( ) . .

, looks_like_number, FLAGS [2]. . true, true , false, false.


+9

Source: https://habr.com/ru/post/1546007/


All Articles