I am just unable to find "truncate a string to a specific length" in Perl. Is there any built in way?
UPDATE:
input: $str = "abcd";
output (truncate for 3 characters): $str is abc
Truncate the string (first argument) if it is longer than the given maximum string length (second argument) and return the truncated string with a ... ending. The inserted three dots at the end should also add to the string length.
This function truncates (reduces) the size of the file specified by FILEHANDLE to the specified LENGTH (in bytes). Produces a fatal error if the function is not implemented on your system.
Perl | length() Function length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Return: Returns the size of the string.
You want to use the substr()
function.
$shortened = substr( $long, 0, 50 ); # 50 characters long, starting at the beginning.
For more, use perldoc
perldoc -f substr
In your case, it would be:
$str = 'abcd'; $short = substr( $str, 0, 3 );
For a string of arbitrary length, where truncate length can be longer than string length, I would opt for a substitution
$str =~ s/.{3}\K.*//s;
For shorter strings, the substitution will not match and the string will be unchanged. The convenient \K
escape can be replaced with a lookbehind assertion, or a simple capture:
s/(?<=.{3}).*//s # lookbehind s/(.{3}).*/$1/s # capture
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With