Add a symbol at the beginning of a line and add the same symbol at the ending of the line using perl

StackOverflow https://stackoverflow.com/questions/17746249

  •  03-06-2022
  •  | 
  •  

Question

I was practising perl assignments online and found this in Sandbox.

How to Write a perl script which adds -> to the front and <- to the end of each line. It then reports the number lines, the length of the longest line, and the total number of bytes in the original input. For instance, the input file

//Input File 
    Hi there.
    This is Fred.
    Who are you?

Should produce the output:

//Output File
    ->Hi there.<-
    ->This is Fred.<-
    ->Who are you?<-
    3 lines, longest 13 characters, 37 bytes total.

I am able to add -> only at the start of the line with this code :

#!/usr/bin/perl
use strict;
use warnings;

open(FH,"input.pl") or die "cannot open file: $!\n"; #Input File
open(NEWFH,"> output.pl") or die "cannot write\n"; #Output File
print "opened file\n";
while(<FH>){
  print NEWFH "-> $_ ";
}
close FH;
close NEWFH; 

Can you please help me add the "->" at the end of the line

Was it helpful?

Solution 2

Simply add it after the line the same way, by including it at the end of the printed string:

chomp; # Strip off newline character
print NEWFH "-> $_ <-\n"; # Add newline ay the end

As far as longest string and total count: you can use 2 variables to store the current max length and current total, and calculate them with the help of the length function. Keep a third variable for line count.

OTHER TIPS

As an exercise, you might take these one-liners and work out how they work:

perl -pe  's/^/->/; s/$/<-/;' input.txt
perl -ple '$_ = "->$_<-";'    input.txt

For a more verbose version, you add the -MO=Deparse switch.

Recommended reading:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top