in reply to Question on SV internals

Your question is a bit confusing as you cannot do a numeric operation on a string like "20 ducks in a row" when warnings and use strict are in force. If the "20" was in a separate variable, once it is used in a numeric context, the string part of that variable doesn't matter anymore. What happens with leading zeroes illustrates this point...

Below, $a starts out as a string with leading zeroes. Adding "0" to it (use in a numeric context), causes the "leading zeroes" to be eliminated, i.e. it is now a binary numeric value. The original string value of $a is now not accessible by any normal Perl operation (you won't know how many leading zeroes it had to begin with). If further math operations are done on $a, no further string to binary conversions are required. Perl math operations are very fast.

Leading zeroes in a numeric assignment like shown below for $b, causes the numeric value to be interpreted as an octal number.

#!/usr/bin/perl -w use strict; my $a = '00000022'; my $b = 00000033; #leading zero means octal! print "$a $b\n"; #00000022 27 $a+=0; print "$a $b\n"; #22 27 #22 now numeric
Update: -- extraneous verbage that added nothing deleted.

Replies are listed 'Best First'.
Re^2: Question on SV internals
by syphilis (Archbishop) on May 08, 2011 at 08:22 UTC
    Your question is a bit confusing as you cannot do a numeric operation on a string like "20 ducks in a row" when warnings and use strict are in force

    No - you *can* do the numeric operation on that string if warnings and strict are enabled, and it gives the same result as you get without strict and warnings ... except, of course, that you additionally get a warning:
    C:\>perl -Mstrict -Mwarnings -e "my $x = '20 ducks in a row'; $x += 17 +;print $x" Argument "20 ducks in a row" isn't numeric in addition (+) at -e line +1. 37 C:\>
    Cheers,
    Rob
Re^2: Question on SV internals
by John M. Dlugosz (Monsignor) on May 09, 2011 at 21:52 UTC
    I was thinking of taking a field that I'm originally using for a numeric value and adding some other (optional) flags to it. Making it a string comparison would give funny results for 4 vs 20, etc. Splitting it up into different fields first, or setting it up with additional (mostly unused) fields originally would be more work.

    I was assuming that using "20 ducks" as a numeric value just worked (albeit with a warning I can turn off in a tight scope). I would not expect the "ducks" to disappear, as I'll look at that part of the string later.

      The read the tutorial on pack and unpack. The advantage of pack "NA20", 20, "ducks" is that it sorts fantastic and fast and that the numeric part and the string part are well-defined separated from eachother.


      Enjoy, Have FUN! H.Merijn