#!/usr/bin/perl use strict; # using strict and warnings will help you spot typos and other guff use warnings; use 5.024; # 1204380 my $string = 'tryna'; # you didn't give us an example of the data so using this my (@slurp, $line, @found); # declare vars; bad for to do as globals, but simpler to read @slurp = ; # read each line of __DATA__ into var $slurp; for $line(@slurp) { # read thru array @slurp line by line if( $line =~ m/($string)/gs ) { # if the current line contains $ string push @found, $line; # and push it to array, @found } } say @found; # ... whose elements get printed to console, here. # you can redirect the scripts output to a file or write a # few more lines here to have the script write it to a file # or, of course, you can use any one of many methods to # catch JUST the searchstring and surrounding words (why?") # NB: this will cause a warning about an unitiialized var in Line 5; # simple enuf but not immediately an issue for OP and, IMO, adding another loop # will just be confusing at this time. __DATA__ 123456 7890 abcd3e fc this sentence has for bar tryna much too long for my taste this doesn't have the magic phrase 123456 7890 abcd3e fc. much too long for my taste but tryno tryna foo bar baz bat bingo and has the magic phrase endit