Create VSTRING from a scalar variable without using eval

I'm just wondering - is it even possible to create a v-string from a scalar variable without resorting to eval ?

I am. e., this works, but uses eval :

 my $var = 'v1.2.3'; my $conversion = to_vstring_1($var); # Prints "Version: 1.2.3, type: VSTRING" printf("Version: %vd, type: %s\n", $conversion, ref \$conversion); sub to_vstring_1 { my ($arg) = @_; $arg =~ tr/0-9.//cd; $arg = 'v' . $arg; return eval $arg; } 

These two options also work and don't use eval , but instead of "VSTRING" they print "SCALAR":

 my $conversion_2 = to_vstring_2($var); # Prints "Version: 1.2.3, type: SCALAR" printf("Version: %vd, type: %s\n", $conversion_2, ref \$conversion_2); my $conversion_3 = to_vstring_3($var); # Prints "Version: 1.2.3, type: SCALAR" printf("Version: %vd, type: %s\n", $conversion_3, ref \$conversion_3); sub to_vstring_2 { my ($arg) = @_; $arg =~ tr/0-9.//cd; $arg = pack('U*', split(/\./, $arg)); return $arg; } sub to_vstring_3 { my ($arg) = @_; $arg =~ tr/0-9.//cd; $arg =~ s/[._]?(\d+)/chr($1 & 0x0FFFF)/eg; return $arg; } 

So, is there a fourth way to do this?

+6
source share
1 answer

can you even create a v-string from a scalar variable without resorting to eval ?

Yes, it is, but it is pain and there is no good reason.

You can write XS code that:

  • parses your input string
  • converts numbers to their char equivalents
  • assigns v-string magic to your scalar with sv_magic call

However, this is exactly what the internal Perl_scan_vstring function in toke.c does . Why reinvent the wheel?

+3
source

All Articles