0

At the moment I am reading lines from a file, chomp them, and replace tabs by spaces, like so:

open( my $xpfh, '<', $xpathfile ) or die "cannot open file $xpathfile";
    chomp( my @xplines = <$xpfh> );
    close $xpfh;

    foreach my $xpline (@xplines) {
        $xpline =~ s/\t/ /g;
...

As you can see, chomping happens outside the foreach loop, but substitution occurs each iteration. How would one bring that action outside the foreach loop, closer to the chomping? I am asking because I would assume that this is faster than each iteration run a regular expression. Either way, it would be syntactically more pleasing to have all structural operations happen in the same block.

5
  • Slurping entire file is already enifficient as long as you deal with non-trivial sizes. You might want to read line-by-line and move chomp into that loop too instead. Commented Feb 25, 2016 at 11:34
  • Example input/output would be good; Commented Feb 25, 2016 at 11:43
  • 1
    How do you know that it's inefficient? Have you benchmarked it? Commented Feb 25, 2016 at 14:39
  • @MattJacob No, that's why I am asking Commented Feb 25, 2016 at 16:10
  • 1
    My point is, don't assume it's inefficient until you have reason to believe it is. What you're doing is called premature optimization. Commented Feb 25, 2016 at 16:18

1 Answer 1

2

I would probably do it without slurping the file into an array, then iterating the array:

while ( <$xpfh> ) {
    chomp;
    s/\t/ /g;
    print;
}

If you do need the array for some other reason though:

s/\t/ /g for @xplines;
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.