Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

How do I delete the first n characters on a line

by CyCliC (Novice)
on Jul 18, 2001 at 11:51 UTC ( #97571=perlquestion: print w/replies, xml ) Need Help??

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

How do I delete the first n characters on a line

Originally posted as a Categorized Question.

  • Comment on How do I delete the first n characters on a line

Replies are listed 'Best First'.
Re: how do i delete the first n characters on a line
by jmcnamara (Monsignor) on Jul 18, 2001 at 12:28 UTC
    Use substr:
    # substr EXPR,OFFSET,LENGTH,REPLACEMENT my $n = 3; my $str1 = "1234567890\n"; my $str2 = substr($str1, $n); print $str1; # 1234567890 print $str2; # 4567890

    John.
    --

Re: How do I delete the first n characters on a line
by ar0n (Priest) on Jul 18, 2001 at 12:28 UTC
    substr($str, 0, $n) = "";
Re: How do I delete the first n characters on a line
by tachyon (Chancellor) on Jul 19, 2001 at 05:43 UTC

    You could also use a regex although this is not as fast as substr.

    my $n = 3; my $str = "1234567890\n"; $str =~ s/^.{$n}//s; # was: $str =~ s/^.{$n}(.*)$/$1/s; print $str;

    The difference with the regex solution is that if $n > length $str no change will be made. With substr you will get a null string left in $str if you try to delete more chars than exist in $str. You need the /s modifier to make the . match a newline which is a valid char.

    cheers

    tachyon

    To get the same behavior as a substr solution use: $str =~ s/^.{1,$n}//s;

    Edit by tye to incorporate I0's reply

      #a simpler regex is
      $str =~ s/^.{$n}//s #or, if you want a null string left in $str if you try to delete more chars than exist in $str,
      $str =~ s/^.{1,$n}//s

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://97571]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2021-04-21 04:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?