Michael Morris Michael Morris - 7 months ago 8
Perl Question

How can i make perl print first ten lines of a string?

Im trying to show the first ten lines of a large string ( first 10 lines of a paragraph)

I've tried to use:

$lines = head-10 $string


I saw some examples that use while loops but my script cant facilicate that, I need it to be a variable.

next i tried to use:

$string = perl -pe'$.>10&&last'


sorry if it seems like a silly question, i have no real background in coding, ive just used some basic bash

which gave me the desired result by typing

String= "$(string | head -n10)"

Answer

If you want to do this in the code, split the paragraph into a list, use an array slice to get the first 10 elements and join them back together again by adding the newlines back.

#!/usr/bin/perl

use strict;
use warnings;


my $string = "line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12";

#  turn the lines into a list by splitting on newline
my @lines = split "\n", $string;

#  take an array slice of the first 10 list items and join them into a string
#  delimited by a newline
my $first_ten = join "\n", @lines[0 .. 9];

#  print your 10 lines
print $first_ten;