How to strip spaces out of a string in perl
How to strip spaces out of a string in perl
You have a variable string that may have blank spaces at the end of the string or at the start of the string and you need to remove these spaces so that you can make use properly of the value of that variable.
Scenario
1 2 |
//You want to strip spaces from the left side and right side of the bellow string and obtain "username" $val_string= ' username '; |
Solution
Create a function which is more feasible to use across all your project:
1 2 3 4 5 6 7 |
sub trim($) { my $string = shift; $string =~ s/^\s+//; $string =~ s/\s+$//; return $string; } |
Then just call the function wherever you need the spaces at the end or at the start of the string removed.
1 2 |
$my_new_val = &trim($val_string); print "My new username is: $my_new_val\n"; |
Output
1 |
My new username is: username |
This will only be working if you want to strip at the end or at the start of the string, you can of course break the function down and use only one side of them if you wish, but in most cases you want to make sure that you removedĀ spaces in both sides.