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

What's the easiest way of printing the first n characters of a scalar (within a script)?

Thanks.

  • Comment on Printing First n Characters of a Scalar

Replies are listed 'Best First'.
Re: Printing First n Characters of a Scalar
by Aristotle (Chancellor) on Aug 20, 2004 at 20:48 UTC
    substr $scalar, 0, $n

    Makeshifts last the longest.

Re: Printing First n Characters of a Scalar
by Grygonos (Chaplain) on Aug 20, 2004 at 20:47 UTC

    Sounds like homework to me. If it's not I apologize. What have you tried? take a look at perlre or substring (<edit> duh.. substring rofl..you can emulate pop via a substitution which I had done recently and that was sticking in my head)</edit> if you haven't already.

Re: Printing First n Characters of a Scalar
by Zaxo (Archbishop) on Aug 20, 2004 at 20:50 UTC

    substr, print substr $string, 0, $n;

    After Compline,
    Zaxo

Re: Printing First n Characters of a Scalar
by superfrink (Curate) on Aug 21, 2004 at 03:28 UTC
    Answers already abound so if it were for homework I'd be tempted to submit something like the following. That said I once put this in an assignment:
    printf("Segmentation fault\n"); sleep(4); printf("just kidding. it's all good.\n");
    My TA didn't find it as funny as I did. When she was a younger student and working late (ie 2 AM) someone put a similar printf() in someone else's assignment while the person went out for a cigarette. That wasn't so funny either. Now back to the perl question:
    sub first_n_chars($$) { my $N = int shift; my $input = shift; my $output = ""; for(;$N > 0; $N--) { $input =~ m/(.)/; $output .= $1; } return $output; } sub first_n_chars_2($$) { my $N = int shift; my $input = shift; my $dots = ""; for(;$N > 0; $N--) { $dots .= '.'; } my $output = ""; $input =~ m/($dots)/; $output .= $1; return $output; } sub first_n_chars_3($$) { my $N = int shift; my $input = shift; my $output = ""; $input =~ m/(.{$N})/; $output = $1; return $output; } my $foo = "314159"; print "$foo\n"; print first_n_chars(1, $foo) , "\n"; print first_n_chars_2(2, $foo) , "\n"; print first_n_chars_3(3, $foo) , "\n";

    Update: Changed " s/$BLAH//; " to " m/$BLAH/; "
Re: Printing First n Characters of a Scalar
by bgreenlee (Friar) on Aug 20, 2004 at 20:48 UTC
Re: Printing First n Characters of a Scalar
by Zed_Lopez (Chaplain) on Aug 20, 2004 at 21:46 UTC
Re: Printing First n Characters of a Scalar
by Anonymous Monk on Aug 20, 2004 at 23:50 UTC

    Start with a scalar that's n characters long and print it.

    Note: Sorry, today's Friday and I just couldn't help it ;-P