Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a scalar variable $temp.
$temp = "DATA\n File\n Hello\n";
How would I create a reg ex that would find the line "File" in the scalar and copy the next line to a new scalar. In this case since "Hello" follows "File", I'd like to copy "Hello" to a new scalar. I know this may seem simple but I've been up all night programming and can't figure it out.

Replies are listed 'Best First'.
Re: Finding a line in a scalar, and copying it to a new scalar?
by ysth (Canon) on Jan 16, 2006 at 07:52 UTC
    Something like this:
    $temp = "DATA\n File\n Hello\n"; ($line) = $temp =~ /^\s*File\n(.*\n)/m;
    That is, search for a line with optional leading whitespace and ending with "File", and capture the following line.
Re: Finding a line in a scalar, and copying it to a new scalar?
by davido (Cardinal) on Jan 16, 2006 at 07:50 UTC

    Something like this would probably do:

    use strict; use warnings; my $temp = "DATA\nFile\nHello\nAnother line\n"; my $found; if( $temp =~ m/File\n(^.*$)/m ) { $found = $1; print $found, "\n"; }

    ...I like the anchors in this regex, but there are a lot of other ways to craft the RE. Or you could to it this way instead:

    my @lines = split /\n/, $temp; foreach my $idx ( 0 .. $#lines ) { next unless $lines[ $idx ] =~ m/File/; $found = $lines[ $idx + 1 ]; print $found; last; }

    Dave

Re: Finding a line in a scalar, and copying it to a new scalar?
by McDarren (Abbot) on Jan 16, 2006 at 07:51 UTC
    Update: I just re-read the OP and realised that you'd asked for a regex solution. In which case you could replace the split line below with:
    my ($a, $b, $c) = $temp =~ m/(\w+)\n/g;

    (The same comment still applies re assigning to a list).

    This is pretty trivial, just split on \n. eg:

    #!/usr/bin/perl -w use strict; my $temp = "DATA\nFile\nHello\n"; my ($a, $b, $c) = split(/\n/, $temp); print "$a:$b:$c\n";

    Although, if you have an unknown number of "lines", then you are probably better off spliting them into a list, like so:

    my @list = split(/\n/, $temp);

    Cheers,
    Darren :)