Re: Simple Encryption question
by jeffa (Bishop) on Dec 29, 2003 at 20:14 UTC
|
This is trivial in Perl. :)
$str =~ tr/0-9/A-Z/;
Of course, this only works if the data is good. You'll have to verify that first.
UPDATE:
And note that this is not secure encryption!
UPDATE2:
Since i got downvoted, looks like i will have to explain why i chose A-Z and not A-J ...
the reason is simple - so the OP won't make that typo again - if it was a typo ... sigh
| [reply] [d/l] |
Re: Simple Encryption question
by Zaxo (Archbishop) on Dec 29, 2003 at 20:19 UTC
|
($_ contains a line of the file)
substr( $_, 0, 16) =~ tr/0-9/AB\-C-HJK/;
That will make the substitution directly in $_ . A substitution like this is not sturdy encryption, just an obscuration.
Update: Changed tr string to fit the spec.
| [reply] [d/l] |
|
|
Thank you perlmonks for the help.
substr works fine in my case. yeah, this is by no means a robust encryption.
One more question: How do i skip the first and last lines of the file from this substitution? The first and last lines are headers and footers of the file and needs to be preserved.
thanks. I am revisiting perl after a long time and am rusty. So, appreciate all your help.
| [reply] |
|
|
It depends on how your header and trailer data look like. If they do not start with numerics, then it's easy...
while (<$filehandle>) {
tr/blah/blah/ if /^\d{16}/; # do the translation
print; # output result
}
If your header and trailer look similar to the rest of the data, and if your file is small, you could read everything in to memory first...
my @data = <$filehandle>;
print $data[0]; # print first line
for (1..$#data-1) { # skip first and last line
$data[$_] =~ tr/blah/blah;
print $data[$_];
}
print $data[-1]; # print last line
Otherwise it will get a bit messy.
| [reply] [d/l] [select] |
|
|
open F, $file or die $!;
my @data = <F>;
for my $i ( 0..$#data ) {
if ( $i == 0 or $i == $#data ) {
#first or last line so do whatever
print $data[$i];
}
else {
# not first or last line
$data[$i] =~ s#^(\d{16})#$_ = $1; tr/0-9/A-J/; $_#e
print $data[$i];
}
}
| [reply] [d/l] |
|
|
|
|
|
Re: Simple Encryption question
by Paladin (Vicar) on Dec 29, 2003 at 20:14 UTC
|
I am assuming your mapping in the question is wrong, and should be 0=A, 1=B, 2=C... 9=J. If not, change it in the code.
$var =~ tr/0-9/A-J/;
perldoc perlop and look for the tr// operator for more info. | [reply] [d/l] |
Re: Simple Encryption question
by Roger (Parson) on Dec 29, 2003 at 20:16 UTC
|
my $number = "0123456789012345";
$number =~ tr/0123456789/AB-CDEFGHK/;
| [reply] [d/l] |
Re: Simple Encryption question
by hardburn (Abbot) on Dec 29, 2003 at 20:14 UTC
|
Is this homework? If so, I'm not going to help you. If not, why are you using such naive encryption in a real program?
| [reply] |