Home > Software design >  Appending to each line of array
Appending to each line of array

Time:11-15

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;

CodePudding user response:

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

CodePudding user response:

Use the map function:

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

CodePudding user response:

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;

CodePudding user response:

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

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

CodePudding user response:

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

CodePudding user response:

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;
  •  Tags:  
  • perl
  • Related