Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Apologies for wasting your time with a badly worded question.

You may have an XY problem. Might be a good time to state what it is you are really trying to accomplish. Could be that this thing with using the previous line is not the best approach.

I'm looking to alter a value in the current line, and then have that value saved to the previous line for use in the next iteration of the loop.

??

The code you posted does exactly that. Maybe this will show it more clearly?

#!/usr/bin/perl use strict; use warnings; my $previous_line = <DATA>; print " prev\tcurrent\n"; while ( my $current_line = <DATA> ) { chomp for ( $previous_line, $current_line ); print "input:\t$previous_line\t$current_line\n"; my @previous_cols = split ' ', $previous_line; my @current_cols = split ' ', $current_line; $current_cols[1] += $previous_cols[1]; $previous_line = $current_line = join ' ', @current_cols; print "output:\t$previous_line\t$current_line\n"; print "\n"; } __DATA__ nul 0 foo 1 bar 2 baz 3 qux 4
Output:
prev current input: nul 0 foo 1 output: foo 1 foo 1 input: foo 1 bar 2 output: bar 3 bar 3 input: bar 3 baz 3 output: baz 6 baz 6 input: baz 6 qux 4 output: qux 10 qux 10

update: reworked example code to not use a sub


The way forward always starts with a minimal test.

In reply to Re^3: How to loop over two lines, alter a value in the current line and save it to the previous line? by 1nickt
in thread How to loop over two lines, alter a value in the current line and save it to the previous line? by rjc33

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2024-04-19 10:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found