Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Assembly language

by SkinBlues (Acolyte)
on Dec 14, 2019 at 18:06 UTC ( [id://11110125]=perlquestion: print w/replies, xml ) Need Help??

SkinBlues has asked for the wisdom of the Perl Monks concerning the following question:

hello everyone, my name is Jack. I'm 21, I am trying to get more involved in this website as I think I can learn a lot here. Do you have any thoughts on assembly language? How could it relate to Perl? What is assembly language useful for?

Thank you

Replies are listed 'Best First'.
Re: Assembly language
by haukex (Archbishop) on Dec 14, 2019 at 22:50 UTC
    What is assembly language useful for?

    I'd say:

    • On a modern machine, understanding at least roughly how assembly / machine instructions* work helps you understand how some code you wrote in a compiled language such as C will be translated. For example, your typical C program is structured into various functions you've written yourself, library functions etc., but assembly is just a linear list of instructions; understanding how one is translated to the other will give you a deeper understanding of what you are actually telling the processor to do when you write your code.
    • You could use it to program small 8 or 16-bit microcontrollers; however, nowadays there are C compilers for most microcontrollers.

    If your goal is to just get a deeper understanding of how compilations and processors work, I actually wouldn't recommend trying to learn modern x86 - the list of instructions has grown ludicrously long. So unless you have some specific reason for needing to know x86 assembly, like you're trying to debug something at that level, you're looking at very specific optimizations, etc., I'd suggest looking at a much simpler microcontroller, such as a Microchip 8-bit PIC, or for example the Atmel ATmega328 (now owned by Microchip as well). The latter is the basis of the Arduino Uno, it's got an instruction setPDF that's not too huge.

    Modern hardware has grown pretty complex, which is why learning the concepts on a simpler embedded system is IMHO helpful: How a processor stores its instructions, fetches them, executes them, reading and writing from/to RAM to do so, interrupts, various buses, low-level "peripherals" (like UART controllers), and so on. All of these concepts translate (more or less) to modern machines, except that they are much more complex there. But the basic building blocks of how a CPU communicates with the rest of the hardware in the system are the same.

    * Note: Many people use the term "assembly" interchangeably with "machine instructions", and in many cases this is true, assembly is often just a textual 1-to-1 representation of the actual binary instructions the processor will directly execute. But to translate that textual representation into a binary format requires a translator program, and often these add a few features that actually mean that the "assembly" is not exactly the same as the machine instructions. But they're close enough that this distinction often doesn't matter.

    How could it relate to Perl?

    Perl is several steps away from assembly. The perl interpreter, which parses your Perl code into an intermediate representation and executes that, is itself written in C, which of course is compiled to machine instructions. So it's not like Perl code is directly translated to machine code - perl is an interpreter.

    From your node here:

    If assembly is fundamental, and machine code is the most fundamental, why would I have to download a program to run it? I do not want to download a program to be able to run it. There should be a way to access the processor directly (possibly through terminal) where I could write "000 101 100 ..." and have it output "101 001" (these numbers do not mean anything real)

    The reason it's not that simple is that on a modern machine there are tons of of intermediate steps and layers. Take the "Hello, World" examples from this Introduction to UNIX assembly programming or this NASM Tutorial:

    • You need to edit and store the textual assembly program, which requires pretty much all components of the computer and OS (on modern machines and modern OSes, trying to learn to input binary assembly would be a gargantuan task).
    • You need to install the program that will take your textual assembly program and translate it to binary representation (e.g. GNU Assembler or NASM, or others for Windows), plus the step of linking.
    • Something as seemingly simple as running a binary is already a pretty complex topic: The OS needs to find the binary on the hard disk (a complex interaction in itself), load that into RAM, and ask the processor to run that; the processor then needs to fetch the instructions it is to run. (Compare this to a small microcontroller, where the program memory and RAM are contained entirely on the same chip and are directly accessible to the CPU.)
    • You need to consider that your assembly program can't "just take" something from the command line or standard input and "just output" something - all of these tasks require you to interact with the operating system, which provides and abstracts these I/O services. Your suggestion of "access[ing] the processor directly" will not really work due to security restrictions of the OS and processor. (If you wanted something as simple as you seem to be asking about, then you could consider something like the Arduino Button Tutorial as the basis for how to actually do really raw I/O with a processor - maybe wish for an Arduino Starter Kit for Christmas? ;-) )
    • Once your assembly program has been compiled to a binary, then yes, you don't necessarily need to download anything other than the binary itself, however, that binary will be specific to the processor architecture, OS, and libraries it was compiled for. (If your goal is to write code that gets compiled down to binary machine instructions, then there are much better ways to do so than assembly, such as C, which is still very close to the hardware and machine code, but much nicer to code in relative to assembly.)

    It's all these layers that make your question pretty broad and hard to answer better without knowing more about why you're asking - I could suggest you could get a degree in Computer Engineering, then you'd learn about all of the above topics, but perhaps you're looking for something more specific?

      I just remembered: The game "Human Resource Machine" (Windows/Linux/Android/iOS) is something I recently tried out and liked; unlike some of the other "intro to programming" games that let you move someone around the screen and that have control structures like loops and if/else, its "programs" are actually quite like assembly.

Re: Assembly language
by GrandFather (Saint) on Dec 15, 2019 at 06:56 UTC

    I have lots of thoughts on assembly language. At $work I am currently working on an embedded system where I need to produce a high performance real time signal processing system. At present essentially all the code is written in C++ and the compiler does a good job of generating efficient code. But I need to have a good understanding of assembly language to satisfy myself that that is the case. There are small pieces of code that are critical to the performance of the system. I know that I can do a better job than the compiler for those bits, but at present I'm not sure I need the extra speed so I'm sticking to C++ for now.

    Higher level languages (in this case C++) are generally much easier to work with and the code is easier to maintain. But, if you understand the processor well enough, assembly language can generally give a factor of two or so speed boost. None of that relates to Perl. An understanding of assembly language now is largely the domain of embedded systems designers and compiler writers. Personally I think these days there is little to be gained to help understanding higher level languages and computers by understanding assembly language. Applications are so far isolated from the processor they are running on that "understanding" what is going on at the processor level is more likely a disadvantage when using Perl and similar scripting languages than it is an advantage. It's rather like trying to understand the physiology of neurons to gain an understanding of personality - it's in there somewhere, but there are so many layers in between that there is no useful cognitive connection between the two domains.

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
Re: Assembly language
by marto (Cardinal) on Dec 14, 2019 at 20:35 UTC

    Welcome, it really depends on what you want to achieve. Historically assembler was in the majority of cases faster than interpreted languages, however with modern optimising compilers for most use cases there's a lot to be said for high level languages, in so much as portability and lower barrier for entry, time it take tho throw something together. Embedded systems, microcontrollers and alike are targets for assembler use, and of course there are other specific use cases. The wiki article elaborates on this and other somewhat niche use cases. One of the previous responses touches on assembly and perl. What are your interests? Often knowing this can help advise further.

Re: Assembly language
by Anonymous Monk on Dec 14, 2019 at 18:53 UTC
Re: Assembly language
by shmem (Chancellor) on Dec 22, 2019 at 00:53 UTC

    There is an interesting connection between perl and assembly as jcb already noted. Yes, perl is implemented in C, but its runtime makes a syntax tree or execution stack out of the program it runs, which looks like a baroque FORTH engine. This old language also has an interpreter and compiler built in, and is a macro language for assembly (which in turn is a macro language for machine code).

    One could say that "perl is to C what FORTH is to assembly". The major difference is that FORTH passes its parameters on the stack, while C makes heavy use of registers - which could also be done by FORTH at compilation of new FORTH words, given its capabilities of introspection.

    When I retire, I might (if I have still interest in that sort of stuff, that is) tackle an implementation of perl in FORTH, create a perl CPU and die rich. Hah!

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
Re: Assembly language
by BillKSmith (Monsignor) on Dec 14, 2019 at 23:30 UTC
    Assembly language is seldom needed except in imbedded applications where computing power is limited due to hardware cost, power, cooling, or physical space. Such programs are usually written "stand-alone" (The overhead of any OS is unacceptable). The programmer has the freedom to make the processor do anything that it is capable of. On the other side, he has the onus to do everything. (Input of a single character can be complicated.) It is possible to write very efficient code, but this depends on the skill of the programmer. (Remember, he has no tools to optimize his code.) Few programmers can optimize their code better than the compiler of almost any modern language can.
    Bill
      Assembly language is seldom needed except in imbedded applications

      Even in embedded systems, assembler is now rarely used. I'm working for a company developing embedded systems since 2015, and we haven't written a single line of assembler during that time. I know that some very old projects had a few lines of assembler, back when the company started 25 years ago, when 8051 was state of the art. AVR and ARM processors are generally programmed in C, or at least we do so. On larger ARM processors, C++ is also used. For us, the border line is the user interface. Code written for bare metal is written in C, code written to run on (embedded) Linux is written in C++, Code written for Windows is written in C#.

      Why?

      1 - Modern C compilers generate highly optimized assembler code. It is very hard to manually produce that code quality. Granted, it is sometimes hard to read, especially when compiled with -O2 or -O3, but you rarely have to read it.

      2 - C code can be reused. To name just a trivial example: Our system clock and software timer library was written years before I was hired, when AVR processors were state of the art. It was written in C. Porting it to ARM processors required just recompiling it. Making it run on 80x86, Z80, 6502 or 68000 will also require just recompiling it. It does not contain any processor-specific or machine-specific code. You need a little piece of code that will be called from a hardware interrupt, but that's in a driver for the library, and generally needs less than 100 lines of code. If that software timer library had been written in assembler, we would have to rewrite it from scratch for every new processor family.

      3 - The vendor-supplied interface to the microcontroller is now C. You get a C/C++ toolchain (often GCC) and a ton of C headers that describe the entire controller. Hardware register access is either memory mapped (ARM) or well hidden behind C preprocessor macros (AVR). If you wish, you can still write assembler code, but you generally don't.

      4 - You don't have to learn machine-specific assembler code. It is good to have an idea of what the processor can do easily (adding 8 bit integers) and what is hard (e.g. floats, integer division, misaligned memory access), but you generally write C, no matter what processor you are using.

      5 - Debugging at C source code level is standard. You really have to confuse processor and debugger to make it fall back to a disassembly listing. In other words: When C source code level debugging does not work any more, something has gone horrible wrong, and assembler knowledge won't get you out of that situation.

      6 - When running on top of Linux, Windows, or any other (general purpose) operating system, writing assembler code does not make any sense. If your code runs too slow, you need a real-time OS and/or a faster machine and/or a different approach to the basic problem. Assembler will rarely help you.


      A note on the different approach: We often split the problem into a real-time task running on bare metal on a sufficiently fast microcontroller and a user interface task running on a general-purpose OS. That way, the microcontoller can do its job as efficient as possible, and only needs to look at the input from the user interface every few milliseconds. All of the fancy eye candy happens on the general purpose OS, burning tons of CPU cycles, without disturbing the real-time task. Every few seconds, when some user hits the touch screen, an event is generated, transformed, and ends as a short message in a buffer of the microcontroller. Or something interesting happens on the real-time side, a short message is send through the general-purpose OS into the user interface task, and makes the screen draw craploads of animations.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        It became hard to write assembly code because CPU evolved to be efficient targets for compilers.

        But self modifying machine code can do miracles if it comes to speed, not sure if C is capable of this.

Re: Assembly language
by jcb (Parson) on Dec 16, 2019 at 01:54 UTC

    The Perl 5 interpreter has its own special quasi-assembly language implemented using C macros. If you are interested in this dialect of assembly, which is useful for writing complex XSUB modules, you should read the documentation for perlxs, perlxstut, perlapi, perlguts, and perlembed as a start.

      I'd rather the op-code the machine code of an theoretical "Perl CPU"

      The C-macros are more alike ASM macros helping abstracting away complicated concepts, like variable types.

      The whole comparison is quite wobbly because Perl is many abstraction layers away from machine code.

      • Machine code
      • Assembler
      • Macro Assembler
      • C
      • Perl
      But also technologies like
      • memory management
      • dynamic typing
      • garbage collection
      • lexical scoping
      • contextual syntax
      • ...

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        While the implementation sits several layers up the stack from the actual hardware, perl is a VM implementing a specialized processor optimized for running Perl code. I vaguely recall a quip somewhere in the XS documentation along the lines of "Real Programmers can write assembly in any language" referring to the macros used in XS code.

        It is hilariously far into the CISC category, but there is a CPU architecture in there. Think of perl itself as microcode...

Re: Assembly language
by LanX (Saint) on Dec 14, 2019 at 18:23 UTC
    Homework?

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

      No I am not in school, personal interest
Re: Assembly language
by harangzsolt33 (Chaplain) on Dec 14, 2019 at 18:22 UTC
    Perl has very little to do with assembly language. Assembly language is machine-specific, while perl is designed to run on any platform. If you write an assembly program for Linux, it won't run on DOS or Windows. So, even if the program is designed to do a very simple task such as calculate the value of PI. No file access needed. No internet access needed. No libraries have to be loaded. Just do a bunch of calculations and print the result to the screen. This assembly program will be fast, but it will only run on one specific OS. If you want it to run on just about any computer, then you should write it in Perl. If your goal is speed, then write it in assembly. If you want the calculations to happen inside a web browser upon visiting a website, then you should write it in JavaScript.

    I like Perl, because it allows me to write programs that run on both Linux and Windows. And I am right now transitioning from using Windows to Linux. What better way to become familiar with Linux than to learn how to program Linux! It's like having a foot in the door. The cool thing about Perl is that if you are a perl programmer, you have full control over DOS, Linux, Windows, OSX, and you can also be a backend developer! Just have to learn ONE language. That's all.

      "If you write an assembly program for Linux, it won't run on DOS or Windows. So, even if the program is designed to do a very simple task such as calculate the value of PI. No file access needed. No internet access needed. No libraries have to be loaded. Just do a bunch of calculations and print the result to the screen. This assembly program will be fast, but it will only run on one specific OS. If you want it to run on just about any computer, then you should write it in Perl"

      Yet more fundamentally flawed advice, given your recent postings I'm not sure if you are just trolling.

      Update: your home node states "The very first programming language I learned was QBASIC when I was 12 years old. Then I was taught C and x86 assembly", how this can link up with your claims above is beyond me.

        Okay, let me prove my point. Here is a little assembly program that displays the message "Hello World" in the terminal window. That's all it does. Nothing complicated. It's the equivalent of print "Hello World"; in perl.

        The interesting thing about this particular asm code is that it will only run on 64-bit Intel and AMD microprocessors. It will not run on a 32-bit CPU. And it will not run on ARM, SPARC, or old iMac processors!

        On the other hand, the print "Hello World"; perl equivalent of this program is not bound to one particular architecture or one particular OS. It would run on any CPU and any OS.

        To further prove my point, if you would run an assembler to convert this asm text code to an obj file and then link the obj into exe file, it would result in a Windows executable. If you tried to run it in Linux, it wouldn't run (without wine). If you tried to execute it on an Apple MacBook Pro, it wouldn't run. It wouldn't run even if you included it in your perl script inline. This code is not only machine specific, but it is OS specific. That's what I meant. It's a fact. Try it if you don't believe me.

        A simple print "Hello World" perl script will run on any computer, but once you insert asm code into your perl script as inline assembly, chances are you have limited your perl script to one particular processor and one particular OS! Now, your perl script is no longer compatible with 90% of other computers out there. But if you omit the inline assembly code, then it will run on other computers.

        section .data Message db "Hello World", 0Dh, 0Ah MessageLength EQU $-Message section .text Start: sub RSP, 8 sub RSP, 32 mov ECX, STD_OUTPUT_HANDLE call GetStdHandle mov qword [REL StandardHandle], RAX add RSP, 32 sub RSP, 32 + 8 + 8 mov RCX, qword [REL StandardHandle] lea RDX, [REL Message] mov R8, MessageLength lea R9, [REL Written] mov qword [RSP + 4 * 8], NULL call WriteFile add RSP, 48 xor ECX, ECX call ExitProcess
      "Perl has very little to do with assembly language"

      This is wrong as well.

      *All* high-level languages are compiled into assembly/machine code to be understood by the processor(s).

      "If you want it to run on just about any computer, then you should write it in Perl. If your goal is speed, then write it in assembly."

      If you want to run something on any computer, use any language that can compile into machine code for the specific CPU architecture you're targeting.

      If your goal is speed, write it in a compiled language (eg. C) instead of a scripting language.

      If your goal is to write something that is so low-level that there isn't a compilation routine to do accurate translation, write it in assembly.

      > If you write an assembly program for Linux, it won't run on DOS or Windows.

      That's plain wrong.

      Both operating systems can run on the same CPU.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        "If you write an assembly program for Linux, it won't run on DOS or Windows.

        That's plain wrong.

        No, it's not wrong. (Please re-read what I wrote, and then read what you wrote. We're talking about two different things. You totally I mean TOTALLY misunderstood my statement! And you're responding to a statement that I never meant to write.)

        DOS programs call INT 21h. In Windows programs, there's the Windows API, and Linux has its own service libraries. The way the EXE headers are written in Windows is totally incompatible with Linux headers. And if you try to execute a Linux program in DOS or vice versa, it won't even load, because the OS does not recognize it as a valid executable. You know what I am talking about, so don't pretend that this isn't true.

      My understanding is that assembly language is a more simpler, fundamental language than languages like Perl and Javascript. Is that right? How could I write a program in assembly language?

        It's definitely fundamental. Assembly is machine code, the lowest level code a computer processor can understand directly. It's the foundation of all high(er) level programming languages, including scripting languages such as Perl.

        My understanding is that assembly language is a more simpler, fundamental language than languages like Perl and Javascript. Is that right? How could I write a program in assembly language?

        Yes, assembly is the most fundamental level. To write assembly programs, you need a compiler ((correction: you need an assembler)) that translates your human readable text file into binary code that runs on either DOS, Windows, Linux, OSX, or the boot sector. You need to pick a platform first. Each of these environments requires your program to work slightly differently, so you can't just write an assembly program that will work on all computers and all platforms. That's what I meant earlier when I said it is machine specific and OS specific. There are different processors. 64-bit processors use different assembly instructions than 32-bit processors. Cell phones use different instructions. There are various processors, and you have to decide which one you want to study first.

        I studied the Intel 80386 processor myself, and I wrote programs for DOS and the boot sector. And in order to do that, you have to download a program called A86.COM. To write Windows assembly programs, you can download FASM.EXE or something similar. In Linux, I am not sure what you would use. I encourage you to ask more questions. Do more research.. Until then, here is a simple assembly program which I wrote for DOS (16-bit):

        ; ; This program can add two very large unsigned integers. ; The program must receive two numbers in base 10 as ; parameters, and it prints the result to STDOUT. ; The biggest number you can possibly end up with has ; 125 digits. This limit is because DOS parameter string ; is stored in a 127-byte string space starting at DS:0081H. ; Written by Zsolt in Dec 15, 2018. ; ; ; To compile & run, enter the following commands: ; ; C:\>TASM ADD ; ; C:\>TLINK /t /c /x ADD ; ; C:\>ADD 3333 55555 ; 58888 ; C:\> ; ; ; CODE SEGMENT ASSUME CS:CODE, DS:CODE, ES:CODE, SS:CODE ORG 256 MAIN: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; See if we've got any parameters. PUSH CS POP DS ; DS <- CS PUSH CS POP ES ; ES <- CS MOV SI,00080H ; SI <- points to parameter string length MOV DI,OFFSET ARGS ; DI <- points to ARGS parameter table LODSB CMP AL,3 ; Parameter string must have at least 3 bytes JB No_Number ; Save the first two parameters. ; (SI now points to the first character of the parameter string.) CALL GrabArgument ; Get first number CALL GrabArgument ; Get second number JMP Add_Numbers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; This function finds the next word in the parameter ; string and saves a pointer for future reference. ; Also, it saves the length of the parameter word. ; ; This function populates the ARGS parameter table. ; The ARGS parameter table consists of 4-byte objects. ; The first 2 bytes are the length of a word, followed ; by a 2-byte pointer to the last letter of word. ; If the word contains anything other than digits (0-9), ; then the program ends prematurely. ; ; DS:SI <- pointer to parameter string ; ES:DI <- pointer to ARGS parameter table ; ; This function increments SI and DI. ; GrabArgument: XOR CX,CX CLD NextChar: CMP SI,0100H ; DOS parameters cannot be longer than 128 byte +s JAE No_Number LODSB CMP AL,13 JE No_Number ; End of string? CMP AL,32 JBE NextChar ; Skip whitespace ; We continue this way only if we've got something ; other than a space or tab. ; Normally in C language, pointers always point to the ; first character of a string, but in this program, ; parameter pointers will point to the last letter ; of a string, because we start adding numbers ; from right to left. CountLen: INC CX ; Count the length of string LODSB CMP AL,32 JBE End_of_Number CMP AL,'0' JB No_Number CMP AL,'9' JBE CountLen No_Number: MOV DX,OFFSET About JMP Print_and_Exit End_of_Number: XCHG CX,AX STOSW ; Save string length DEC SI MOV AX,SI DEC AX STOSW ; Save ptr to the end of string RET ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Prepare for addition. ; Add_Numbers: ; Figure out which number is longer. MOV SI,OFFSET ARGS LODSW ; Load length XCHG CX,AX LODSW ; Skip pointer XCHG BP,AX ; BP = number1 ptr LODSW ; Load next word's length CMP CX,AX ; AX > CX ? JA CX_BIGGER XCHG CX,AX CX_BIGGER: ; Now CX holds the length of the longest string. LODSW XCHG SI,AX ; SI = number2 ptr MOV DI,OFFSET Result-1 ; DI = destination ; Now we have the following setup: ; SI points to the last letter of the first number ; BP points to the last letter of the second number ; DI points to the last letter of the result XOR DX,DX ; DL = carry flag STD NextDigit: ; START ADDING DIGITS ; ; Here make sure that tonce we get an invlaid value in AL ; invalid digit, we assume all digits are 0 after that. ; or if we're past the end of word. ; CALL GetDigit ; Read from number 1 XCHG BX,AX ; digit -> BX XCHG BP,SI ; Read from number 2 CALL GetDigit ; digit -> AX ADD AL,BL ; Add the two digits ADD AL,DL ; Add carry MOV DL,DH ; Reset carry (DL=0) ADD AL,'0' CMP AL,'9' ; Carry? JBE NO_CARRY SUB AL,10 INC DX ; Set carry (DL=1) NO_CARRY: STOSB ; write result LOOP NextDigit ; Note: DH is always 00. CMP DL,DH ; Is carry set? JE DONE MOV AL,'1' STOSB DONE: MOV DX,DI INC DX Print_and_Exit: MOV AH,9 INT 21H ; Print text MOV AX,4C00H INT 21H ; Exit 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; This function reads the next digit of the number ; into register AL. If we reach the end of the number, ; then AL will be 0, and our pointer (SI) will stay ; in place, otherwise SI will jump to the next digit. ; (Keep in mind we're reading from right to left.) ; ; DS:SI <- pointer to base 10 number string ; AL -> raw value ; GetDigit: LODSB ; digit -> AX SUB AL,'0' CMP AL,10 ; is AL < 10 ? JB ValidRange ; Looks like we reached the end of the number. MOV AL,DH ; AL=0 INC SI ValidRange: RET ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ARGS contains a 2-byte pointer to a parameter word, ; followed by a 2-byte string length, followed by the ; pointer to the next parameter, followed by its length. ; Initially, ARGS contains 2 pointers to a blank string ; of zero length. ; About DB 10,13, "This program adds two positive integers of any +size and displays the result." DB 10,13, "Usage: ADD <number> <number>", 10,13 DB 10,13, "Example: ADD 19333045834565223108349833745893453 129 +82372388169001", 10,13 DB 10,13, "This program requires two numbers as parameters." DB 10,13, "The parameters may only contain digits (0-9).",10,13 +,10,13 Result DB "$" ; The program will either display the About message, or ; it will display a number. If we display a number, then ; we will overwrite the About message with digits. ARGS DW 0, OFFSET Blank, 0, OFFSET Blank Blank DW 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; CODE ENDS END MAIN


        Now, here is the same program in Perl. See, how shorter and simpler this is?:

        #!/usr/bin/perl -w use strict; use warnings; my $ABOUT = "This program adds two positive integers of any size and d +isplays the result.\n" . "Usage: ADD <number> <number>\n\n" . "Example: ADD 19333045834565223108349833745893453 12982372 +388169001\n\n" . "This program requires two numbers as parameters.\n" . "The parameters may only contain digits (0-9).\n\n"; @ARGV == 2 or die $ABOUT; if (Is_Not_A_Number($ARGV[0]) || Is_Not_A_Number($ARGV[1])) { die $ABOUT; } print ADD($ARGV[0], $ARGV[1]); exit; #################################### sub ADD { my $A = defined $_[0] ? $_[0] : ''; my $B = defined $_[1] ? $_[1] : ''; my $AL = length($A); my $BL = length($B); my $i = ($AL > $BL) ? $AL : $BL; my $CARRY = 0; my $SUM = '0'; my $X; while ($i-- > 0) { $X = $AL ? vec($A, --$AL, 8) : 48; $X += ($BL ? vec($B, --$BL, 8) : 48) + $CARRY; $CARRY = $X > 105 ? 1 : 0; vec($SUM, $i, 8) = $X - ($CARRY ? 58 : 48); } return ($CARRY ? '1' : '') . $SUM; } #################################### sub Is_Not_A_Number { @_ or return 1; my $N = shift; return 1 unless defined $N; my $L = length($N); return 1 unless $L; my $C; while ($L-- > 0) { $C = vec($N, $L, 8); return 1 if ($C < 48 || $C > 57); } return 0; }
Re: Assembly language
by Anonymous Monk on Dec 18, 2019 at 03:47 UTC
    Today, I would consider it fair to say that modern-day processor architectures are no longer designed to be programmed by human beings using assembly language. Instead, they are designed to be programmed using optimizing compilers. And, the vendors of those chips work carefully with compiler-designers (and, produce compilers themselves ...) which will produce "optimal" code sequences in particular situations. Assembly language today is confined to extremely edge-case situations such as the /arch subdirectory of the Linux kernel source-tree.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11110125]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-25 07:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found