Here's an off-the-cuff version that uses regular expressions:

#!/usr/bin/perl use strict; use warnings; my $str = qq(just wondering how i can have perl display part of my lon +g memo. basically i want the first lets say 255 charachters of the p +aragraph. im really new to perl so i don't know how i would come abo +ut this?); my $max = 50; (my $copy = $str) =~ s/(.{1,$max})\b.*/$1.../; print "$copy\n"; __END__

What it does is match a maximum of $max characters and stores that in $1, a word boundary, then the rest of the string and essentially replaces the entire string with whatever it matched in $1 and an ellipsis. Matching the word boundary is nice so that you don't chop off the text in the middle of a word.

Update: Here's another way that does essentially the same thing:

my ($short) = $str =~ m/(.{1,$max}\b)/; $short .= '...';

This is probably how I would do it in my code, I just happened to think of the other way first for some reason.


In reply to Re: Display shortened paragraph by duff
in thread Display shortened paragraph by Anonymous Monk

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.