Why can the circumflex sign be used for control ch

2019-06-22 09:41发布

问题:

I just came across an answer on SO with a curious syntax:

How do I include a newline character in a string in Delphi?

MyString := 'Hello,' + ^M + ^J + 'world!';

I've been using Delphi for several years now, but I didn't know you could use the circumflex sign for control characters.

Is this just a left over from the early Delphi or Turbo Pascal days?

Should it be used nowadays?

PS: I'm not asking about advice on the line break characters, there is sLineBreak and other methods as discussed in the original question.

回答1:

Yes this is a legacy from days of yore.

And no you should not get into the habit of using this feature. Remember that code is read more often than it is written. Always think of your readers who most likely won't know what that syntax means.



回答2:

No, it is not from Turbo Pascal days. It is from decades before TP, and before DOS, and probably even before UNIX. Something old like first 300 bit-per-second dialup modems and DEC VT-52 terminal, RT-8 OS on PDP-8 machine and early version of C. Or maybe even more old - though everything more old to me is mere legends :-).

"^" sign is shortcut for "Ctrl" key. So ^C in traditional convention stands for Ctrl+C in Microsoft notation. That notation used for textmode menus ion DOS times, like in Aforementioned Turbo Pascal, Norton Utilities, DOS Navigator, etc.

Out of my memory you can consider "^" for "subtract 64".
So as Chr(65) is 'A' then Chr(1) would be ^A.
And ^@ would be #0 :-) AFAIR in DOS times pressing Ctrl+Shift+"2/@" would actually produce #0 in BIOS keyboard buffer :-)
^[ would AFAIR be #27 aka Esc char - and if you run telnet.exe you would see it prompted for escape character.

So TP chosen to follow the time-blessed convention, and then rules of backward compatibility engaged. Personally, i take 'bla-bla'^M^J'foo-baz' literal more string-like than 'bla-bla'#13#10'foo-baz' when you want it on one line. And constructing the value with plus is better fit when your literal takes several source lines.

The pity is that syntax highlighting in Delphi IDE is hopelessly broken on those constants.



回答3:

Yes, this is left over from TP days. You could also write your statement like this

mystring:= 'Hello'#13#10'world!';

which is probably less obscure and more easily understandable than using ^M and ^J. Of course, you should really define constants

const
 crlf = #13#10

begin
 mystring:= 'Hello' + crlf + 'world!';
end;