These "snippets" will generate a "numbered sourcecode listing" in a variety of styles.

Why'd I post these, because I couldn't find any snippets (i saw all 456 of 'em), and even though it was relatively easy, someone might find it useful (since this is the 5th time I created some from scratch).

Also, there was some golf potential ;)(gotta start somewhere)

Reading material (if you don't know how it works):
perlfunc:printf,perlop,perlrun,perldata

# style: what i like (my latest first two attempts) perl -e"printf('%4s: %s',++$a,$_)while(<>)" file perl -e"printf'%4s: %s',++$a,$_ while<>" file # then i did a lot of searching, and ran accross clemburg's solution # (which was 'broken' like the craft version, see end) perl -pe "s/^/++$i.' 'x4/e" file # then i remembered -p and broke it down to ### which is by far my favorite (the one i use) perl -pe "printf'%4s: ',++$a" file # style: merlyn (as featured in WebTechniques) perl -pe"printf'%6s ','='.++$a.'='" file # or more acurately perl -pe"printf'%-6s ','='.++$a.'='" file # or most accurately (since his output looks like' =2= code +') perl -pe"printf'%8s%-8s ','','='.++$a.'='" file # style: [craft] (craft doesn't handle 3digits well) # you can always change the 2 into 3 to handle 3 digit nums perl -pe"printf'%-2s: ',++$a" file
update:
########## my favorite (never forget perlvar, thanks davorg) perl -pe "printf'%4u: ',$." file # or to prevent 'overflow' perl -pe "printf'%4.4s: ',$." file

Replies are listed 'Best First'.
Re: numbered sourcecode listing (oneliners)
by davorg (Chancellor) on Jul 20, 2001 at 13:39 UTC
Re: numbered sourcecode listing (oneliners)
by jmcnamara (Monsignor) on Jul 20, 2001 at 13:52 UTC

    Here is a golf style effort:
    perl -pe'$_=$..$".$_' file

    But this doesn't really meet crazyinsomniac's requirements. So how about this: ;-)
    perl -e 'print `cat -n $ARGV[0]`' file


    John.
    --

Re: numbered sourcecode listing (oneliners)
by merlyn (Sage) on Jul 21, 2001 at 02:48 UTC
      You can omit the caret in that one too.
         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print
        You can omit the caret in that one too.
        Only if I was golfing and not worried about being clear and working in all circumstances. I never trust the empty match, since it depends on the most recent successful match. True, here, it defaults to an empty string, but why count on that when one single character fixes that problem and communicates the proper intent?

        -- Randal L. Schwartz, Perl hacker