http://qs321.pair.com?node_id=163231

lolly has asked for the wisdom of the Perl Monks concerning the following question:

Hi, this program outputs strings which are greater in length than 250 characters (each string begins with '>'). however, i am trying to wrap the string so that it prints 60 characters per line, and its not working. The program runs fine but the wrapping doesn't work. where am i going wrong??
#! /usr/local/bin/perl -w use strict; open (INPUT, $ARGV[0]) or die "unable to open file"; my $count = 1; my $line; while (<>) { chomp; $line = $_; $line =~ s/(.{60})/$1\n/g; if (/>/) { ++$count; } print "\>$count\n", $_, "\n\n" if length $_ >= 250; } close INPUT;

Replies are listed 'Best First'.
Re: why won't it wrap??
by tadman (Prior) on May 01, 2002 at 10:40 UTC
    Maybe if you printed $line instead of $_? You've faked yourself out it seems.

    Also, you're opening INPUT but not actually using it. You're still reading that file because, coincidentally, that is what <> does.

    A little touch up:
    use strict; my $count = 0; open (INPUT, $ARGV[0]) || die "Could not read $ARGV[0]\n"; foreach my $line (<INPUT>) { chomp ($line); $line =~ s/(.{60})/$1\n/g; $count += />/g; print ">$count\n$line\n\n"; } close (INPUT);
    I'm not entirely sure why you're only printing split lines.
    A reply falls below the community's threshold of quality. You may see it by logging in.
(cLive ;-) Re: why won't it wrap??
by cLive ;-) (Prior) on May 01, 2002 at 10:42 UTC
    You're not printing $line. You're printing $_.

    cLive ;-)

      thanks cLive ;-), you were spot on. lolly ;-)
Re: why won't it wrap??
by Maclir (Curate) on May 01, 2002 at 14:46 UTC
    Have you considered Text::Wrap?