The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

String::Tools - Various tools for manipulating strings.

SYNOPSIS

 use String::Tools qw(
    define
    is_blank
    shrink
    stitch
    stitcher
    stringify
    subst
    subst_vars
    trim
    trim_lines
 );

 my $val = define undef; # ''

 say is_blank(undef);    # 1  (true)
 say is_blank('');       # 1  (true)
 say is_blank("\t\n\0"); # 1  (true)
 say is_blank("0");      # '' (false)

 say shrink("  This is  a    test\n");  # 'This is a test'

 ## stitch ##
 say stitch( qw(This is a test) );  # "This is a test"
 say stitch(
    qw(This is a test), "\n",
    qw(of small proportions)
 );  # "This is a test\nof small proportions"

 # Format some other language in a more readable format,
 # yet keep the resulting string small for transport across the network.
 say stitch(qw(
    SELECT *
      FROM table
     WHERE foo = ?
       AND bar = ?
 ));
 # "SELECT * FROM table WHERE foo = ? AND bar = ?"

 ## subst ##
 my $date = 'Today is ${ day } of $month, in the year $year';
 say subst( $date,   day => '15th', month => 'August', year => 2013   );
 # OR
 say subst( $date, { day => '15th', month => 'August', year => 2013 } );
 # OR
 say subst( $date, [ day => '15th', month => 'August', year => 2013 ] );

 my $lookfor = 'The thing you're looking for is $_.';
 say               subst( $lookfor, 'this' );
 say 'No, wait! ', subst( $lookfor, _ => 'that' );

 say trim("  This is  a    test\n");    # 'This is  a    test'

 # Describe what to trim:
 say trim("  This is  a    test\n",
          l => '\s+', r => '\n+');      # 'This is  a    test'

DESCRIPTION

String::Tools is a collection of tools to manipulate strings.

VARIABLES

$BLANK

The default regular expression character class to determine if a string component is blank. Defaults to [[:cntrl:][:space:]]. Used in "is_blank( $string = $_ )", "shrink( $string = $_ )", "stitch( @list )", and "trim( $string = $_ ; $l = qr/$BLANK+/ ; $r = $l )".

$SUBST_VAR

The regular expression for the "subst( $string ; %variables = ( _ => $_ ) )" function. Starts with an alphabetic or underscore character, continues with any number of word characters, and then is followed by any number of subpatterns that begin with a single punctuation character and is followed by one or more word characters.

If you want to change it for a particular use, it is highly recomended that you local'ize your change.

$THREAD

The default thread to use while stitching a string together. Defaults to a single space, ' '. Used in "shrink( $string = $_ )" and "stitch( @list )".

FUNCTIONS

define( $scalar = $_ )

Returns $scalar if it is defined, or a defined but false value (which works in a numeric or string context) if it's undefined. Useful in avoiding the 'Use of uninitialized value' warnings. $scalar defaults to $_ if not specified.

is_blank( $string = $_ )

Return true if $string is blank. A blank $string is undefined, the empty string, or a string that conisists entirely of "$BLANK" characters. $string defaults to $_ if not specified.

shrink( $string = $_ )

Trim $BLANK characters from that lead and rear of $string, then combine multiple consecutive $BLANK characters into one $THREAD character throughout $string. $string defaults to $_ if not specified.

stitch( @list )

Stitch together the elements of list with "$THREAD". If an item in @list is blank (as measured by "is_blank( $string = $_ )"), then the item is stitched without "$THREAD".

This approach is more intuitive than join:

 say   join( ' ' => qw( 1 2 3 ... ), "\n", qw( Can anybody hear? ) );
 # "1 2 3 ... \n Can anybody hear?"
 say   join( ' ' => qw( 1 2 3 ... ) );
 say   join( ' ' => qw( Can anybody hear? ) );
 # "1 2 3 ...\nCan anybody hear?"
 #
 say stitch( qw( 1 2 3 ... ), "\n", qw( Can anybody hear? ) );
 # "1 2 3 ...\nCan anybody hear?"

 say   join( ' ' => $user, qw( home dir is /home/ ),     $user );
 # "$user home dir is /home/ $user"
 say   join( ' ' => $user, qw( home dir is /home/ ) ) .  $user;
 # "$user home dir is /home/$user"
 #
 say stitch( $user, qw( home dir is /home/ ), '', $user );
 # "$user home dir is /home/$user"

stitcher( $thread => @list )

Stitch together the elements of @list with $thread in place of "$THREAD".

 say stitcher( ' ' => qw( 1 2 3 ... ), "\n", qw( Can anybody hear? ) );
 # "1 2 3 ...\nCan anybody hear?"

 say stitcher( ' ' => $user, qw( home dir is /home/ ), '', $user );
 # "$user home dir is /home/$user"

stringify( $scalar = $_ )

Return an intelligently stringified version of $scalar. Attempts to avoid returning a string that has the reference name and a hexadecimal number: ARRAY(0xdeadbeef), My::Package=HASH(0xdeadbeef).

If $scalar is undefined, returns the result from "define( $scalar = $_ )". If $scalar is not a reference, returns $scalar. If $scalar is a reference to an ARRAY, returns the stringification of that array (via "@$scalar"). If $scalar is a reference to a HASH, returns the stringification of that hash (via "@{[%$scalar]}"). If $scalar is a reference to a REF, and $$scalar is not reference to a REF, calls itself as stringify($$scalar). If $scalar is a reference to a SCALAR, calls itself as stringify($$scalar). If $scalar is a reference that is not one of the previously mentioned, returns the default stringification (via "$scalar").

Since v0.18.277

subst( $string ; %variables = ( _ => $_ ) )

Take in $string, and do a search and replace of all the variables named in %variables with the associated values.

The %variables parameter can be a hash, hash reference, array reference, list, scalar, or empty. The single scalar is treated as if the name is the underscore. The empty case is handled by using underscore as the name, and $_ as the value.

If you really want to replace nothing in the string, then pass in an empty hash reference or empty array reference, as an empty hash or empty list will be treated as the empty case.

Only names which are in %variables will be replaced. This means that substitutions that are in $string which are not mentioned in %variables are simply ignored and left as is.

The names in %variables to be replaced in $string must follow a pattern. The pattern is available in variable "$SUBST_VAR".

Returns the string with substitutions made.

subst_vars( $string = $_ )

Search $string for things that look like variables to be substituted.

Returns the unique list of variable names found, without the leading $ or surrounding {}.

 my $string = 'Name is $name, age is $age, birthday is ${ birthday }';
 my @vars = subst_vars($string);    # 'name', 'age', 'birtday'

trim( $string = $_ ; $l = qr/$BLANK+/ ; $r = $l )

Trim string of leading and trailing characters. $string defaults to $_ if not specified. The paramters l (lead) and r (rear) are both optional, and can be specified positionally, or as key-value pairs. If l is undefined, the default pattern is /$BLANK+/, matched at the beginning of the string. If r is undefined, the default pattern is the value of l, matched at the end of the string.

If you don't want to trim the start or end of a string, set the corresponding parameter to the empty string ''.

 say foreach map trim, @strings;

 say trim('  This is a test  ')
 # 'This is a test'

 say trim('--This is a test==', qr/-/, qr/=/);
 # '-This is a test='

 say trim('  This is a test!!', r => qr/[.?!]+/, l => qr/\s+/);
 # 'This is a test'

trim_lines( $string = $_ ; $l = qr/$BLANK+/ ; $r = $l )

Similar to "trim( $string = $_ ; $l = qr/$BLANK+/ ; $r = $l )", except it does it for each line in a string, not just the start and end of a string.

 say trim_lines("\t This \n\n \t is \n\n \t a \n\n \t test \t\n\n")
 # "This\nis\na\ntest"

 say trim_lines( "\t\tThis\n\t\tis\n\t\ta\n\t\ttest", qr/\t/ );
 # "\tThis\n\tis\n\ta\n\ttest"

Since v0.18.270.

BUGS

Please report any bugs or feature requests on the bugtracker website https://github.com/rkleemann/String-Tools/issues

When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.

TODO

Nothing?

SEE ALSO

stitch is similar to "join" in perlfunc.

subst is similar to any templating system.

VERSION

This document describes version v0.19.045 of this module.

AUTHOR

Bob Kleemann <bobk@cpan.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2014-2019 by Bob Kleemann.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)