Basically I have some very long variables and need only the first few characters.
I tried using this regex, but it doesn't work.
$va开发者_Python百科r =~ s/(^.{20})?/$1/g;
It doesn't do anything to it.
Any help would be appreciated.
$var = substr($var,0,20);
Note that the simpler:
substr($var,20) = '';
will croak if the string is less than 20 characters.
Or using substitution (assuming 5.10+):
$var =~ s/^.{20}\K.+//s;
Or using unpack:
$var = unpack 'a20', $var;
substr($var, 20) = "";
deletes characters beyond position 20 in $var
.
This is the substitution you probably had in mind:
$var =~ s/^(.{20}).*/$1/;
精彩评论