my @lines = <>; foreach my $index (0 .. $#lines) { if ($lines[$index] =~ /word/) { # Do what you want here, but to $lines[$index - 1] } }