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

I know this is probably super simple, but I am very new to Perl, and programming (I am learning via tutorials now). I can't seem to find how to do the following (and yes, I have been googling all over for the answer):

My current hosts file format:

1.1.1.1 01computer12 01computer12.abc.com 1.1.1.2 34computer21 34computer21.abc.com
etc etc
I need to append another alias at the end of each line based on the content of the line - so it's not a simple search and replace - and it would look like this:
1.1.1.1 01computer12 01computer12.abc.com 01host12 1.1.1.2 34computer21 34computer21.abc.com 34host21
and so on. Do I read the second column into a variable, edit that variable, then append it to the end of the line? I'm just unsure how to proceed. I'm not asking for anyone to write it for me, I could just use some ideas/direction, or any kind of help you can offer.

Thanks!!!!

Replies are listed 'Best First'.
Re: How to re-arrange and edit lines in a text file
by tybalt89 (Monsignor) on Nov 07, 2016 at 23:16 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1175477 use strict; use warnings; while(<DATA>) { s/^\S+\s+(\d+)computer(\d+).*\K/ $1host$2/; print; } __DATA__ 1.1.1.1 01computer12 01computer12.abc.com 1.1.1.2 34computer21 34computer21.abc.com
Re: How to re-arrange and edit lines in a text file
by BillKSmith (Monsignor) on Nov 08, 2016 at 03:30 UTC
    You can do this with a "one-liner". Read about the run-time switches -i, -p, and -e in perlrun. Use the substitution that Tybalt provided.
    Bill
Re: How to re-arrange and edit lines in a text file
by Anonymous Monk on Nov 07, 2016 at 22:12 UTC

    Hi

    Forget googling and tutorials, how would you solve the problem with pencil and paper?

    Write those steps down, thats step 1 in programming, and be very detailed

    After you've done that post it here

Re: How to re-arrange and edit lines in a text file
by Monk::Thomas (Friar) on Nov 08, 2016 at 15:46 UTC
    Do I read the second column into a variable, edit that variable, then append it to the end of the line? I'm just unsure how to proceed.

    Yes, this is a good approach.

    • read a line (and save it into a variable)
    • parse the line into fields, e.g. by using split
    • calculate value for 'last field' from 2nd field (making sure there actually is a 2nd field) -> usually done by an 'if' with a regexp match condition
    • append value to current line, e.g. by using the .= operator

    Saving the current line into a variable is useful if you want to keep the current line 'as-is'. If you want to get fancy you could also create an intermediate representation of the output in memory (probably as an 'array of arrays') calculate the longest value length for each column and create properly indented columns from scratch.
    Just remember: You can't spell 'pretty pointless' without 'pretty'. ;)