Home: Perl Programming Help: Beginner:
Beginning perl; subroutines

New User

Nov 29, 2012, 11:05 AM

Views: 2556
Beginning perl; subroutines

Hey guys,

So I again, I come to the forums looking for programming guidance. The language that I'm specifically trying to work with today is Perl. So pretty much for my class we're being asked to read in from a file, print out to a new file and use a sub routine for the program. With my knowledge of other programming languages (very limited mind you) I got everything done, except for my sub routine.

My subroutine is supposed to from the read in file take the input for example 21-Nov-1995 and break down the whole numbers into digits and then provide some computations.

so for example 21 = 2 and 1, Nov would be 1 and 1 etc etc.

After reading the chapters this project is supposed to cover I've found not one way to split the digits apart. to be honest the only way I can personally think of based on my past classes would be using a delimiter and even then we haven't covered that in this class yet. So I guess there's a way to do it otherwise?

Any guidance of just how to split up my whole number would be really appreciated (any method or example would do honesty).

Thanks, Shevik

(This post was edited by shevik on Nov 29, 2012, 11:31 AM)

Veteran / Moderator

Nov 29, 2012, 2:47 PM

Views: 2538
Re: [shevik] Beginning perl; subroutines

One way to do it:

my $day = "21" 
my @split_number = split //, $day;
# now, $split_number[0] contains 2 and $split_number[1] contains 1

You could also do it numerically with division and modulus (21 = 2 * 10 + 1), but it's a bit more tedious.


Nov 30, 2012, 8:00 AM

Views: 2531
Re: [shevik] Beginning perl; subroutines

I think that your teacher expects the arithmetic solution that Laurent refers to. Perl has a mod operator (%). Use the perl built-in function "int" (refer: perldoc -f int) in place of the mathematical "floor". (It will work fine for positive numbers) The quirks of floating point numbers should not be a problem in this application.

0 <= number < 100
units = number mod 10
tens = floor(number/10)
Good Luck,