2

In the below code I tried to print every line along with its line number. Is there any other way to optimize the below code using Perl?

#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<","exercise.csv";
while(<$fh>)
{
   print "$.=====>$_";
}
close $fh;
4
  • It depends what you mean by optimize. You can make it more concise by using certain language features. The whole loop can be condensed into print "$.=====>$_" while <$fh>; and you don't have to do the close $fh because it will automatically close the filehandle when $fh goes out of scope. You should include or die $! to catch errors from your open (and in theory also your close, as that could fail, but we've just removed it anyway). But that's really a codereview, which should go on Code Review, not here. Commented Nov 15, 2017 at 13:18
  • Maybe we can benchmark between the print with variable interpolaton, as in posted question, and print with variable concatenation as in print $. .'====>'.$_; Commented Nov 15, 2017 at 21:02
  • If you redirect the output to a file instead of printing to the terminal, it may run faster, especially if it is a large file, since the terminal does not need to render everything.... perl my_script.pl > output Commented Nov 16, 2017 at 7:56
  • What exactly is the problem? Is your program running too slowly? Is it taking up too much memory? Commented Nov 23, 2017 at 13:23

1 Answer 1

3

No.

When you're optimising, you look at things that are less efficient ways of accomplishing the goal. That's often algorithmic, and looking at where looping is occurring is a good start.

But then there's resource usage optimisation - disk IO is often the most expensive operation - but you need to do all the IO that you're doing, and you're not doing any redundant IO.

And sometimes - system calls or 'shelling out' to other binaries (via system or backticks) can incur overhead. But you don't do that either.

Basically - your code is just not complicated enough to have any significant inefficiencies.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.