Martzy
Martzy

Reputation: 85

Split string from file in Perl

So, i have a file to read like this

Some.Text~~~Some big text with spaces and numbers and something~~~Some.Text2~~~Again some big test, etc~~~Text~~~Big text~~~And so on

What I want is if $x matches with Some.Text for example, how can I get a variable with "Some big text with spaces and numbers and something" or if it matches with "Some.Text2" to get "Again some big test, etc".

open FILE, "<cats.txt" or die $!;
while (<FILE>) {
chomp;
my @values = split('~~~', $_);
  foreach my $val (@values) {
    print "$val\n" if ($val eq $x)
  }

  exit 0;
}
close FILE;

And from now on I don't know what to do. I just managed to print "Some.text" if it matches with my variable.

Upvotes: 2

Views: 131

Answers (2)

TLP
TLP

Reputation: 67910

Your best option is perhaps not to split, but to use a regex, like this:

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

while (<DATA>) {
    while (/Some.Text2?~~~(.+?)~~~/g) {
        say $1;
    }
}

__DATA__
Some.Text~~~Some big text with spaces and numbers and something~~~Some.Text2~~~Again some big test, etc~~~Text~~~Big text~~~And so on

Output:

Some big text with spaces and numbers and something
Again some big test, etc

Upvotes: 1

RobEarl
RobEarl

Reputation: 7912

splice can be used to remove elements from @values in pairs:

while(my ($matcher, $printer) = splice(@values, 0, 2)) {
    print $printer if $matcher eq $x;
}

Alternatively, if you need to leave @values intact you can use a c style loop:

for (my $i=0; $i<@values; $i+=2) {
    print $values[$i+1] if $values[$i] eq $x;
}

Upvotes: 2

Related Questions