Your "specification" is a bit vague and the exercise seems rather light, but here's a sketch to give you the flavour of Perl:

while (<>) { my ($prefix, $tail) = /(\S+) (.*)/; print "\n" if $currPrefix && $currPrefix ne $prefix; print "$prefix $tail"; $currPrefix = $prefix; }

which works without change for both redirected input and input files with output to stdout in both cases. However a little more work is required to correctly handle the perl proc.pl infile outfile variant:

#!/usr/bin/perl use strict; use warnings; my $in = *STDIN; my $out = *STDOUT; if (@ARGV == 2) { open $in, '<', $ARGV[0] or die "Can't open '$ARGV[0]': $!\n"; open $out, '>', $ARGV[1] or die "Can't create '$ARGV[1]': $!\n"; } my $currPrefix; while (<$in>) { my ($prefix, $tail) = /(\S+) (.*)/; print $out "\n" if $currPrefix && $currPrefix ne $prefix; print $out "$prefix $tail"; $currPrefix = $prefix; }

which works as expected using redirection or infile/outfile.

An interesting variant is:

#!/usr/bin/perl use strict; use warnings; my $currPrefix; $^I = '.bak'; while (<>) { my ($prefix, $tail) = /(\S+) (.*)/; print "\n" if $currPrefix && $currPrefix ne $prefix; print "$prefix $tail"; $currPrefix = $prefix; }

which will in place edit a list of input files generating backups of the original files with '.bak' extensions.

However, if you are dealing with databases then you are heading into territory where Perl shines so if you like, ask a similar question involving databases.

Perl is the programming world's equivalent of English

In reply to Re: Concatenate records by GrandFather
in thread Concatenate records by Shalmaneser

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.