perltruncation

How to truncate a string to a specific length?


I am unable to find "truncate a string to a specific length" in Perl. Is there any built-in way?

Input: $str = "abcd";

Output (truncate for 3 characters): $str is abc


Solution

  • 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 );