neo33 neo33 - 14 days ago 7
Perl Question

How to get the following substrings using perl?

Hello I am working with a perl script and i have the following variable:

$string1="ZZ:DPHTEST1ZZ";


I would like to build two additional variables by getting a substring from $string1 using ":" as separator, I would like to add two prints in my script with the following outputs:

print $fragment1;
print $fragment2;


to get the following output:

ZZ
DPHTEST1ZZ


I tried with:

$fragment1 = substr $string1, index($string1, ':');
print $fragment1;


but I am getting:

:DPHTEST1ZZ


therefore I would like to appreciate to get this strings, by using the separator, i was researching a little and I just found methods of perl that use the position, thanks for the support,

Answer

The index builtin returns the first position of a string within a string. For your example, index($string1, ':') is 2. If you want your substr to start after the : just add one so you get three.

my $fragment2 =  substr $string1, index($string1, ':') + 1;

To get the stuff on the left of the :, you need to take substr from the beginning of the string to the first occurrence of :.

use strict;
use warnings;
use feature 'say';

my $string1 = "ZZ:DPHTEST1ZZ";

my $left = substr $string1, 0, index( $string1, ':' );
my $right = substr $string1, index( $string1, ':' ) + 1;

say $left;
say $right;

The above approach is useful in SQL1 or other languages that do not include split. However, Perl does include split, so my ($fragment1, $fragment2) = split /:/, $string1 as suggested by Mr. Llama is the more sensible option. It's way more readable.


1) I linked a MySQL documentation here. Note the absence of split and a comment somewhere at the bottom saying that there is no such function including explanations of how to do substr/index instead.

Comments