Search code examples
regexperllinesscalar

How can I keep only the first five lines in a Perl scalar?


From any kind of scalar, what regex could I use to match the first five lines of it and discard the rest?


Solution

  • Odd request, but this should do it:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my $s = join '', map { "$_\n" } 1 .. 9;
    
    my ($first) = $s =~ /^((?:.*\n){0,5})/;
    my ($last) = $s =~ /((?:.*\n){0,5})$/;
    
    
    print "first:\n${first}last:\n$last";
    

    A more common solution would be something like this:

    #!/usr/bn/perl
    
    use strict;
    use warnings;
    
    #fake a file for the example    
    my $s = join '', map { "$_\n" } 1 .. 9;    
    open my $fh, "<", \$s
        or die "could not open in memory file: $!";
    
    my @first;
    while (my $line = <$fh>) {
        push @first, $line;
        last if $. == 5;
    }
    
    #rewind the file just in case the file has fewer than 10 lines
    seek $fh, 0, 0;
    
    my @last;
    while (my $line = <$fh>) {
        push @last, $line;
        #remove the earliest line if we have to many
        shift @last if @last == 6;
    }
    
    print "first:\n", @first, "last:\n", @last;