StarCoder17
StarCoder17

Reputation: 175

Perl split pattern with delimiter at specific position

I have a strings which i wanted to split in perl with delimiter but at specific position. $Str = d2a_orx_lego_clk The output i wanted is d2a_orx , ie split only after second underscore. The code i tried splits the string in two parts but at first underscore not at second.

#!/bin/perl

$str = d2a_orx_lego_clk;
#print join('_', split(/_/, $str )), "\n";
my ($k, $v) = split(/_/, $str, 2);
print "$k\n";
print "$v\n";

Thanks

Upvotes: 0

Views: 319

Answers (2)

Harini
Harini

Reputation: 571

This code below works fine which splits the string with delimiter '_' and then join with same delimiter.

#!/bin/perl
$str = d2a_orx_lego_clk;
my @string = split(/_/, $str);
my $str= join '_',$string[0],$string[1];
print $str,"\n";

Upvotes: 0

ysth
ysth

Reputation: 98388

my ($k, $v) = $str =~ /^([^_]*_[^_]*)_(.*)/;

Using a regex match works, and is much easier than getting split to do what you want.

Upvotes: 4

Related Questions