Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading characters from a file 1

Status
Not open for further replies.

fatherperl

IS-IT--Management
May 22, 2001
1
GB
Hi,

I've only been using Perl for 2 days and am trying to write a basic encryption program. (Not for practical use, just as an example).

I've got the program asking for the cleartext message and the 3 figure key, then it encrypts the 1st character of the cleartext using that the character of the key. My problem is that I can't figure out how to sequentially read characters from the variable (The cleartext message) - I need to read the next, then the next etc... The variable has been defined in a line something like this....

chomp ($cltmessage = <stdin>);

I'd appreciate anyhelp anyone could offer.

Thanks peeps
 
well, you can do it like so:

$string = 'blah';
$len = length($string);
for($i = 0; $i < $len; $i++)
{
$letter = substr($string, $i, 1);
} luciddream@subdimension.com
 
You can use &quot;substr&quot;(substring) - you tell substr where to start, and how many characters you want. Create a loop(while?), and in that loop use substr to grab 1 character at a time from $cltmessage.

Another way to handle it is to use &quot;split&quot; to split up $ctlmessage into an array of 1-character elements, and then user a foreach loop to process each array element:

### when you split with NULL(2slashes right next to each other), then it produces an array of 1-character elements.
my @my_array = split //, $cltmessage;
my $char = &quot;&quot;;
foreach $my_char (@my_array) {
### do something(encrypt?) with $my_char
}

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
You can even simplify hmerrill's method a little more and just use:
Code:
foreach my $char (split(//, $ctlmessage)) {
   # do something with $char
}
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top