Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Pretty cool!

How would one accomplish the following with pyp?

* Wait until one sees a line with a start marker (say 'start:')

* Perform on an operation on the lines until an end marker ('end:') is reached.

Would you do a whole-input operation on stdin to extract the relevant lines first and then operate on the individual lines? Or would you maintain boolean conditionals within the loop?



There are a number of possible options! And remember you can always pipe pyp to pyp. Here are some ideas, in order of what came to mind, where the operation is incrementing.

  pyp 'lines[lines.index("start") + 1:]' | pyp 'lines[:lines.index("end")]' | pyp 'int(x) + 1'
  
  pyp 'start = lines.index("start"); end = lines.index("end", start); map(lambda x: int(x) + 1, lines[start + 1:end])'
  
  pyp 'dropwhile(lambda x: x != "start", lines)' | pyp 'lines[1:]' | pyp 'takewhile(lambda x: x != "end", lines)' | pyp 'int(x) + 1'
  
  pyp 'map(lambda x: int(x) + 1, takewhile(lambda x: x != "end", islice(dropwhile(lambda x: x != "start", lines), 1, None)))'
  
  pyp -b 'cond = False' 'if cond and x == "end": break' 'if cond: print(int(x) + 1)' 'if x == "start": cond = True'


Having moved from Perl to Python many years ago, this is one of those things that Perl has magic to handle, for example:

    perl -lne '$sum += $_ if /start:/ .. /end:/; END{print $sum}' file.txt
With the -n option, perl runs your code for every line in the input (stdin, or filenames). $_ holds the content of the line. And the .. operator is a stateful (!) operator that becomes true when its left part becomes true, until the right part becomes true.

So I write 95% of my code in Python, but for command line magic, it's hard to beat Perl.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: