Pyjava
Pyjava

Reputation: 117

How to get the index or variable length of a value using perl(something like dynamic list length of java)?

I have 2 outputs:-

7: ib1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP>    
9: bondib0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP>

Using perl I want to get the substr ib1 and bondib0. Currently if I set

substr($line,3,3); this will return ib1
substr($line,3,7); this will return bondib0

I want to have a single substr for above, how to do that?

Something like substr($line,3,index($line,":"));

Please let me know how can i have dynamic value for 3 and 7 indexs above it is coming because of lengths of values are different.

Upvotes: 0

Views: 56

Answers (2)

Pyjava
Pyjava

Reputation: 117

To generalise, one Solution I can figure out is below:-

 my $pindex = rindex($line,":");
 $str = substr($line,3,$pindex-3);

This solves the purpose by reading each character.

Upvotes: -1

simbabque
simbabque

Reputation: 54371

Your approach to use substr and index should work. However, there are two other ways to do this.

The easier one is to use a regular expression and do a pattern match.

while (my $line = <DATA>) {
    if ($line =~ m/: ([^:]+):/) {
        print $1, "\n";
    }
}

__DATA__
7: ib1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP>    
9: bondib0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP>

This will match a string on a colon : and a space , and then capture everything that is not a colon, until it encounters another colon. See regex101.com for an explanation, and take a look at perlretut for a gentle introduction to regex.

An alternative would be to use split on a colon and a space. There are only two of them there.

while (my $line = <DATA>) {
    ( undef, my $interface ) = split /: /, $line;
    print $interface;
}

__DATA__
7: ib1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP>    
9: bondib0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP>

It will break the string into pieces on ": ", discard the first part, save the second and discard the rest.

However the regex solution is better.

Upvotes: 5

Related Questions