CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Substring

 



zapzap
User

Nov 19, 2013, 10:42 PM

Post #1 of 7 (2483 views)
Substring Can't Post

Greetings,
I'm trying to do this:

String
Strin
Stri
Str
St
S

I've already completed this task but I was wondering if anyone could make it more of a 'Perl' approach


Code
 

print "Enter a string: ";
chomp(my $s = <STDIN>);
for (0..(length($s)-1)) {
print substr($s,0,length($s)-$_),"\n";
}


Let me know?


Laurent_R
Veteran / Moderator

Nov 20, 2013, 8:37 AM

Post #2 of 7 (2479 views)
Re: [zapzap] Substring [In reply to] Can't Post

One possibility, shown under the Perl debugger:


Code
[104693->104693]  DB<1> $_ = "String"; 
[104693->104693] DB<2> print "$_\n" and chop while $_
String
Strin
Stri
Str
St
S
[104693->104693] DB<3>



BillKSmith
Veteran

Nov 20, 2013, 9:22 AM

Post #3 of 7 (2475 views)
Re: [zapzap] Substring [In reply to] Can't Post

I like your method, but use the function 'reverse' rather than your 'do-it-yourself' reversal.

Code
print "Enter a string: "; 
chomp( my $s = <STDIN> );
for ( reverse( 1 .. length $s )) {
print substr( $s, 0, $_ ), "\n";
}

Good Luck,
Bill


Laurent_R
Veteran / Moderator

Nov 20, 2013, 9:56 AM

Post #4 of 7 (2473 views)
Re: [zapzap] Substring [In reply to] Can't Post

Or possibly this (untested):

Code
my $len = length $s; 
say substr $s, 0, $len while $len--;


Update: This is probably better:

Code
my $len = length $s; 
say substr $s, 0, $len-- while $len;



(This post was edited by Laurent_R on Nov 20, 2013, 2:18 PM)


zapzap
User

Nov 20, 2013, 7:23 PM

Post #5 of 7 (2462 views)
Re: [Laurent_R] Substring [In reply to] Can't Post

wow, thanks for the reply. I would have never thought of your approach. I'll have to analyze this one. Thanks again.
zap


(This post was edited by zapzap on Nov 20, 2013, 7:27 PM)


zapzap
User

Nov 20, 2013, 7:35 PM

Post #6 of 7 (2460 views)
Re: [BillKSmith] Substring [In reply to] Can't Post

Thanks, and thanks for the reverse recommendation. I was thinking somebody would've tried implementing map.


zapzap
User

Nov 20, 2013, 7:45 PM

Post #7 of 7 (2459 views)
Re: [Laurent_R] Substring [In reply to] Can't Post

Thanx, this is nice

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives