How does a scalar know what it is?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tom

    How does a scalar know what it is?

    In C, I can just read the K&R book and know
    how everything is pretty much coded at the
    machine level. At least to some extent.

    But how does Perl know when you type

    print $ref

    for example that it is not an integer, string or what have
    you?

    And how does

    print $num; 2 or "Two"

    again at the machine level, how does perl know
    what it has?



  • Jürgen Exner

    #2
    Re: How does a scalar know what it is?

    Tom wrote:[color=blue]
    > In C, I can just read the K&R book and know
    > how everything is pretty much coded at the
    > machine level. At least to some extent.
    >
    > But how does Perl know when you type
    >
    > print $ref
    >
    > for example that it is not an integer, string or what have
    > you?
    >
    > And how does
    >
    > print $num; 2 or "Two"
    >
    > again at the machine level, how does perl know
    > what it has?[/color]

    Wrong way of thinking. Every scalar has a numerical, string, and boolean
    attribute (probably I forgot some). AFAIR a length attribute is also stored
    with each scalar and probably some others.
    Which one is being used depends on the context and perl will compute the
    value if it is not known yet.

    Example:

    my $foo = "1234";
    # the _string_ attribute of $foo contains the four characters '1', '2', '3',
    '4'
    # the numerical attribute is not defined

    my $bar = $foo + 1;
    # the _numerical_ attribute of $foo is now defined as 1234
    # and the _numerical_ attribute of $bar contains the number 1235

    jue


    Comment

    • Joe Smith

      #3
      Re: How does a scalar know what it is?

      Tom wrote:[color=blue]
      > In C, I can just read the K&R book and know
      > how everything is pretty much coded at the
      > machine level. At least to some extent.
      >
      > But how does Perl know when you type
      >
      > print $ref
      >
      > for example that it is not an integer, string or what have
      > you?[/color]

      A scalar variable (SV) is a struct with several flags. The flags
      indicate which elements in the struct have valid values.

      IV = Integer Value
      NV = Numeric (floating point) Value
      PV = Printable string (with LEN=bytes allocated, CUR=current size)
      RV = Reference

      See "perldoc Devel::Peek" for more details.

      #!/usr/bin/perl
      use Devel::Peek;
      $a = '1'.'23'; Dump $a; # String
      $a -= 1; Dump $a; # Integer (not string)
      $_ = "a=$a"; Dump $a; # String (and integer)
      $a *= 1.3; Dump $a; # Float
      $_ = "a=$a"; Dump $a; # String (and float)
      $a = \$_; Dump $a; # Scalar ref
      $a = \@INC; Dump $a; # Array ref
      $a = \%INC; Dump $a; # Hash ref;
      $a = sub {$_}; Dump $a; # Code ref

      Comment

      Working...