2

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.

0

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.