Logo

Programming-Idioms

  • PHP
  • Pascal
  • Fortran

Idiom #71 Echo program implementation

Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.

program x
  implicit none
  character (len=:), allocatable :: a
  integer :: n, i, l
  n = command_argument_count()
  a = ''
  do i=1,n
     call get_command_argument(i, a, l)
     if (l > len(a)) then
        deallocate (a)
        allocate (character(len=l) :: a)
        call get_command_argument(i, a)
     end if
     write (unit=*,fmt='(A)', advance="no") a
     if (i < n) then
        write (unit=*,fmt='(" ")', advance="no")
     else
        write (unit=*,fmt='()')
     end if
  end do
end

a is a buffer which is allocated to the length needed.
echo implode(' ', array_slice($argv, 1)), PHP_EOL;

Use PHP_EOL to be portable. This is ideal if you are printing this text to a terminal.

Alternatively, you can change PHP_EOL to just "\n" (UNIX Line Endings) or "\r\n" (Windows Line Endings) to specify a line ending.
PROGRAM Echo;

VAR
    I: Integer;
BEGIN
    for I := 1 to ParamCount - 1 do
        Write(ParamStr(I), ' ');
    if (ParamCount > 0) then
        Write(ParamStr(ParamCount));
    WriteLn();
END.
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
   for I in 1 .. Argument_Count loop
      Put (Argument (I) & (if I = Argument_Count then "" else " "));
   end loop;
   
   New_Line;
end Main;

New implementation...
< >
christianhujer