Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Perl Problem.


xxSk1N_D33Pxx's Avatar
Member
0 0

I've just started learning this language and have come up against a problem I can't seem to get my head around.

At the moment i have a script that reads content from a file and prints it to the console, however my aim is to append the string '#' to the beginning of each newline, without using a loop.

The following is the code for the script:

#!/usr/bin/perl

$file = '/home/sk1n/test.txt';
open(INFO, $file);
@line = <INFO>;
close(INFO);
print @line;

I'll highly appreciate any input.


ghost's Avatar
0 0

You could try doing a string replace of \r for \r# (or similar, depending on which line break works). Other than that, I don't think there's any way for you to give special attention to each line of a file unless you do a loop. Any particular reason you're against using a loop?


xxSk1N_D33Pxx's Avatar
Member
0 0

Zephyr_Pure wrote: Any particular reason you're against using a loop?

The guide I'm following has not introduced the loop in Perl, yet.

One of the exercises is to append the string '#', although it does not explicitly state that a loop can not be used. I just assumed it couldn't, based on it not introducing them at this point.

However I will look into the method you suggested.

Thank you both for your input, much appreciated.

Edit:

Solved the problem with the following:

<snip>
s/\A/#/ for @line;
</snip>

Thank you Zepyhr_Pure.


clone4's Avatar
Perl-6 Wisdom Seeker
0 0

which is short version for:

for (@line) { $_ =~ s/\A/#/; }

So you still use loop, as everybody said… And I would advice when you are begginer to avoid the shortening of code to one liners as much as possible, firstly it's less readable for your own future reference and at the beginning you should learn how to code things properly… Just my 2 cents


xxSk1N_D33Pxx's Avatar
Member
0 0

Thank you Clone, I never actually knew that was just a shorter version.


clone4's Avatar
Perl-6 Wisdom Seeker
0 0

xxSk1N_D33Pxx wrote: Thank you Clone, I never actually knew that was just a shorter version.

No problem ;) and if you are stuck somewhere don't worry to pm me, or write me on msn. Helping somebody is always good revision :)