Perl split string example
Perl split string example
Perl split string function is one of the few perl functions used in string manipulation. It is similar to explode in php which will create for you an array with the pieces from the specified string. In this post snipped, you will see a quick example of how this can be used in your own projects.
Scenario
We have a string that we know it has specific delimiters. Normally you build the specific string to include the delimiters you need. Anyway, lets say we have the below example:
1 2 |
#!/usr/bin/perl my $string = 'Andrew|Johnny|Bob'; |
The delimiter in our case is “|” as you can see. Based on this character we want to split it and get each of our person names in an array.
Solution
Using the split function, we can split the string based on the rules we use. In normal cases we can just use the strings we want to split, in our case, the character “|“.
1 2 3 4 5 6 7 8 |
#!/usr/bin/perl my $string = 'Andrew|Johnny|Bob'; my @array_str = split('\|', $string); foreach my $name (@array_str) { print "$name\n" } |
I also added a loop to parse the array and print each name individually. For special characters, since you will use these as delimiters, you will notice that we need to escape them, else they will not be properly used in the split. So we use the rule:
1 |
my @array_str = split('\|', $string); |
which has the “\” just before our delimiter.
Output
When running our little script the output should look similar to bellow:
1 2 3 |
Andrew Johnny Bob |
So now we can use the names directly from one little string.
Keep in mind that you can also use regex rules for delimiters, so you can get really complicated if you need to, for instance, say you have numbers as delimiters, you can split this based on the fact that it is a number delimiting your values:
1 2 3 |
#!/usr/bin/perl my $string = 'Andrew1Johnny2Bob'; my @array_str = split('/\d+/',$string); |
That’s it with this, happy coding, cheers!