Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a string to a specific length in perl?

Tags:

perl

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

like image 251
SS Hegde Avatar asked Jan 21 '13 15:01

SS Hegde


People also ask

How do you truncate a string?

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.

What is truncate Perl?

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.

How do I find the length of a string in Perl?

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.


2 Answers

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 ); 
like image 100
Andy Lester Avatar answered Sep 22 '22 00:09

Andy Lester


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 
like image 42
TLP Avatar answered Sep 25 '22 00:09

TLP