开发者

How do I reduce a variable's length to 20 characters in Perl?

开发者 https://www.devze.com 2023-03-07 04:45 出处:网络
Basically I have some very long variables and need only the first few characters. I tried using this regex, but it doesn\'t work.

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/;
0

精彩评论

暂无评论...
验证码 换一张
取 消