PerlNewbie
PerlNewbie

Reputation: 3

Appending to each line of array

I am just starting new to Perl and I came across an exercise that I really cant work out in the set framework. Basically I have been asked to append a '#' symbol to the start of each line in the array. But that I should only need to add in 1 extra line of code and possibly modify one existing line. Here is the code:

$file = '/etc/passwd';          
open(INFO, $file);              
@lines = <INFO>;                
close(INFO);                    
print @lines;

Upvotes: 0

Views: 536

Answers (6)

knittl
knittl

Reputation: 265131

Use the map function:

print map { '#' . $_ } @lines;

Upvotes: 3

Dave Cross
Dave Cross

Reputation: 69224

It looks like you're trying this exercise, which comes from this tutorial. Please don't do that. Why would you want to learn a programming language from a tutorial that starts by saying:

Please note: This tutorial was written in the early 1990's for version 4 of Perl. Although it is now significantly out of date, it was a popular source of information for many people over many years. It has therefore been left on-line as part of the historical archive of the Internet.

You'd be far better off using the (modern) resources listed at learn.perl.org.

The question is flawed anyway. You don't need to add a line of code, you just need to modify an existing one.

print map { "# $_" } @lines;

Upvotes: 1

Gilbert
Gilbert

Reputation: 3776

close INFO;
grep{ $_ = "#$_"; undef } @lines;

Without the undef the grep would assemble a matching array for return, which is discarded. As undef grep will now discard everything. Why this works you need to dig out on your own.

Extra credit: benchmark the different solutions to find the fastest. See the Benchmark module

Upvotes: 0

cppcoder
cppcoder

Reputation: 23095

By adding the first two lines you can achieve that.

$file = "inputfile";
`sed 's/^/#/g' /etc/passwd > inputfile`;
open(INFO, $file);
@lines = <INFO>;
close(INFO);
print @lines;

Upvotes: -1

Karoly Horvath
Karoly Horvath

Reputation: 96258

It's perl, so there are probably dozens of way to do it, here is one:

print "#" . join('#', @lines);

Upvotes: 0

gpojd
gpojd

Reputation: 23055

Use a for loop:

$_ = '#' . $_ for @lines;

I suggest this because map will make a new array while this will modify an existing one. If you want to use map, copy the array back to the original array.

@lines = map { '#' . $_ } @lines; ## possibly slower since it creates a new array then copies it

Upvotes: 5

Related Questions