Sunteți pe pagina 1din 45

What is C language?

The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing system software, though it is also used for writing applications. ...
printf() Function What is the output of printf("%d")? 1. When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after %d so compiler will show in output window garbage value. 2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write printf("%d",a) then compiler first accesses the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location. 3. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(...) and scanf(...). malloc() Function- What is the difference between "calloc(...)" and "malloc(...)"? 1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size). malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...). 2. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available. calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode. printf() Function- What is the difference between "printf(...)" and "sprintf(...)"? sprintf(...) writes data to the character array whereas printf(...) writes data to the standard output device. Compilation How to reduce a final size of executable? Size of the final executable can be reduced using dynamic linking for libraries. Linked Lists -- Can you tell me how to check whether a linked list is circular? Create two pointers, and set both to the start of the list. Update each as follows:

while (pointer1) { pointer1 = pointer1->next; pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next; if (pointer1 == pointer2) { print ("circular"); } } If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, its either 1 or 2 jumps until they meet. "union" Data Type What is the output of the following program? Why? #include main() { typedef union { int a; char b[10]; float c; } Union; Union x,y = {100}; x.a = 50; strcpy(x.b,"hello"); x.c = 21.50; printf("Union x : %d %s %f n",x.a,x.b,x.c); printf("Union y : %d %s %f n",y.a,y.b,y.c); } String Processing --- Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. void PrintPermu (char *sBegin, char* sRest) { int iLoop; char cTmp; char cFLetter[1]; char *sNewBegin; char *sCur; int iLen; static int iCount; iLen = strlen(sRest); if (iLen == 2) { iCount++; printf("%d: %s%s\n",iCount,sBegin,sRest); iCount++; printf("%d: %s%c%c\n",iCount,sBegin,sRest[1],sRest[0]); return; } else if (iLen == 1) { iCount++; printf("%d: %s%s\n", iCount, sBegin, sRest); return; } else { // swap the first character of sRest with each of // the remaining chars recursively call debug print

sCur = (char*)malloc(iLen); sNewBegin = (char*)malloc(iLen); for (iLoop = 0; iLoop < iLen; iLoop ++) { strcpy(sCur, sRest); strcpy(sNewBegin, sBegin); cTmp = sCur[iLoop]; sCur[iLoop] = sCur[0]; sCur[0] = cTmp; sprintf(cFLetter, "%c", sCur[0]); strcat(sNewBegin, cFLetter); debugprint(sNewBegin, sCur+1); } } } void main() { char s[255]; char sIn[255]; printf("\nEnter a string:"); scanf("%s%*c",sIn); memset(s,0,255); PrintPermu(s, sIn); }

What will print out? main() { char *p1=name; char *p2; p2=(char*)malloc(20); memset (p2, 0, 20); while(*p2++ = *p1++); printf(%s\n,p2); } The pointer p2 value is also increasing with p1 . *p2++ = *p1++ means copy value of *p1 to *p2 , then increment both addresses (p1,p2) by one , so that they can point to next address . So when the loop exits (ie when address p1 reaches next character to name ie null) p2 address also points to next location to name . When we try to print string with p2 as starting address , it will try to print string from location after name hence it is null string . e.g. : initially p1 = 2000 (address) , p2 = 3000 *p1 has value n ..after 4 increments , loop exits at that time p1 value will be 2004 , p2 =3004 the actual result is stored in 3000 - n , 3001 - a , 3002 - m , 3003 -e we r trying to print from 3004 . where no data is present that's why its printing null . Answer: empty string.

What will be printed as the result of the operation below: main() { int x=20,y=35; x=y++ + x++; y= ++y + ++x; printf(%d%d\n,x,y) ; } Answer : 5794 What will be printed as the result of the operation below: main() { int x=5; printf(%d,%d,%d\n,x,x<<2,>>2) ; } Answer: 5,20,1 What will be printed as the result of the operation below:

#define swap(a,b) a=a+b;b=a-b;a=a-b; void main() { int x=5, y=10; swap (x,y); printf(%d %d\n,x,y) ; swap2(x,y); printf(%d %d\n,x,y) ;} int swap2(int a, int b) { int temp; temp=a; b=a; a=temp; return 0; } as x = 5 = 00000,0101; so x << 2 -< 00001,0100 = 20; x >7gt; 2 -> 00000,0001 = 1.

Therefore, the answer is 5, 20 , 1 the correct answer is 10, 5 5, 10

Answer: 10, 5 What will be printed as the result of the operation below: main() { char *ptr = Tech Preparation; *ptr++; printf(%s\n,ptr) ; ptr++; printf(%s\n,ptr); } 1) ptr++ increments the ptr address to point to the next address. In the previous example, ptr was pointing to the space in the string before C, now it will point to C. 2)*ptr++ gets the value at ptr++, the ptr is indirectly forwarded by one in this case. 3)(*ptr)++ actually increments the value in the ptr location. If *ptr contains a space, then (*ptr)++ will now contain an exclamation mark. Answer: Tech Preparation What will be printed as the result of the operation below: main() { char s1[]=Tech; char s2[]= preparation; printf(%s,s1) ;} Answer: Tech What will be printed as the result of the operation below: main() { char *p1; char *p2; p1=(char *)malloc(25);

p2=(char *)malloc(25); strcpy(p1,Tech); strcpy(p2,preparation); strcat(p1,p2); printf(%s,p1) ; } Answer: Techpreparation The following variable is available in file1.c, who can access it?: static int average; Answer: all the functions in the file1.c can access the variable.

Operating System Interview Questions And Answers


[Operating System Frequently Asked Questions ,Operating System FAQ ] What's OPERATING SYSTEM? An Operating System, or OS, is a software program that enables the computer hardware to communicate and operate with the computer software. Without a computer Operating System, a computer would be useless. OPERATING SYSTEM TYPES As computers have progressed and developed so have the types of operating systems. Below is a basic list of the different types of operating systems and a few examples of Operating Systems that fall into each of the categories. Many computer Operating Systems will fall into more than one of the below categories. GUI - Short for Graphical User Interface, a GUI Operating System contains graphics and icons and is commonly navigated by using a computer mouse. See our GUI dictionary definition for a complete definition. Below are some examples of GUI Operating Systems. System 7.x Windows 98 Windows CE Multi-user - A multi-user Operating System allows for multiple users to use the same computer at the same time and/or different times. See our multi-user dictionary definition for a complete definition for a complete definition. Below are some examples of multiuser Operating Systems. Linux Unix Windows 2000 Windows XP Mac OS X Multiprocessing - An Operating System capable of supporting and utilizing more than one computer processor. Below are some examples of multiprocessing Operating Systems. Linux Unix Windows 2000 Windows XP Mac OS X Multitasking - An Operating system that is capable of allowing multiple software processes to run at the same time. Below are some examples of multitasking Operating

Systems. Unix Windows 2000 Windows XP Mac OS X Multithreading - Operating systems that allow different parts of a software program to run concurrently. Operating systems that would fall into this category are: Linux Unix Windows 2000 Windows XP Mac OS X What are the basic functions of an operating system?

- Operating system controls and coordinates the use of the hardware among the various applications programs for various uses. Operating system acts as resource allocator and manager. Since there are many possibly conflicting requests for resources the operating system must decide which requests are allocated resources to operating the computer system efficiently and fairly. Also operating system is control program which controls the user programs to prevent errors and improper use of the computer. It is especially concerned with the operation and control of I/O devices. Why paging is used? -Paging is solution to external fragmentation problem which is to permit the logical address space of a process to be noncontiguous, thus allowing a process to be allocating physical memory wherever the latter is available. While running DOS on a PC, which command would be used to duplicate the entire diskette? diskcopy What resources are used when a thread created? How do they differ from those when a process is created? When a thread is created the threads does not require any new resources to execute the thread shares the resources like memory of the process to which they belong to. The benefit of code sharing is that it allows an application to have several different threads of activity all within the same address space. Whereas if a new process creation is very heavyweight because it always requires new address space to be created and even if they share the memory then the inter process communication is expensive when compared to the communication between the threads.

What is virtual memory? Virtual memory is hardware technique where the system appears to have more memory that it actually does. This is done by time-sharing, the physical memory and storage parts of the memory one disk when they are not actively being used. What is Throughput, Turnaround time, waiting time and Response time? Throughput number of processes that complete their execution per time unit. Turnaround time amount of time to execute a particular process. Waiting time amount of time a process has been waiting in the ready queue. Response time amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment). What is the state of the processor, when a process is waiting for some event to occur? Waiting state What is the important aspect of a real-time system or Mission Critical Systems? A real time operating system has well defined fixed time constraints. Process must be done within the defined constraints or the system will fail. An example is the operating system for a flight control computer or an advanced jet airplane. Often used as a control device in a dedicated application such as controlling scientific experiments, medical imaging systems, industrial control systems, and some display systems. Real-Time systems may be either hard or soft real-time. Hard real-time: Secondary storage limited or absent, data stored in short term memory, or read-only memory (ROM), Conflicts with time-sharing systems, not supported by general-purpose operating systems. Soft realtime: Limited utility in industrial control of robotics, Useful in applications (multimedia, virtual reality) requiring advanced operating-system features. What is the difference between Hard and Soft real-time systems? - A hard real-time system guarantees that critical tasks complete on time. This goal requires that all delays in the system be bounded from the retrieval of the stored data to the time that it takes the operating system to finish any request made of it. A soft real time system where a critical real-time task gets priority over other tasks and retains that priority until it completes. As in hard real time systems kernel delays need to be bounded What is the cause of thrashing? How does the system detect thrashing? Once it detects thrashing, what can the system do to eliminate this problem? - Thrashing is caused by under allocation of the minimum number of pages required by a process, forcing it to continuously page fault. The system can detect thrashing by evaluating the level of CPU utilization as compared to the level of multiprogramming. It can be eliminated by reducing the level of multiprogramming. What is multi tasking, multi programming, multi threading? Multi programming: Multiprogramming is the technique of running several programs at a time using timesharing. It allows a computer to do several things at the same time. Multiprogramming creates logical parallelism. The concept of multiprogramming is that

the operating system keeps several jobs in memory simultaneously. The operating system selects a job from the job pool and starts executing a job, when that job needs to wait for any i/o operations the CPU is switched to another job. So the main idea here is that the CPU is never idle. Multi tasking: Multitasking is the logical extension of multiprogramming .The concept of multitasking is quite similar to multiprogramming but difference is that the switching between jobs occurs so frequently that the users can interact with each program while it is running. This concept is also known as timesharing systems. A time-shared operating system uses CPU scheduling and multiprogramming to provide each user with a small portion of time-shared system. Multi threading: An application typically is implemented as a separate process with several threads of control. In some situations a single application may be required to perform several similar tasks for example a web server accepts client requests for web pages, images, sound, and so forth. A busy web server may have several of clients concurrently accessing it. If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time. The amount of time that a client might have to wait for its request to be serviced could be enormous. So it is efficient to have one process that contains multiple threads to serve the same purpose. This approach would multithread the web-server process, the server would create a separate thread that would listen for client requests when a request was made rather than creating another process it would create another thread to service the request. To get the advantages like responsiveness, Resource sharing economy and utilization of multiprocessor architectures multithreading concept can be used. What is hard disk and what is its purpose? Hard disk is the secondary storage device, which holds the data in bulk, and it holds the data on the magnetic medium of the disk. Hard disks have a hard platter that holds the magnetic medium, the magnetic medium can be easily erased and rewritten, and a typical desktop machine will have a hard disk with a capacity of between 10 and 40 gigabytes. Data is stored onto the disk in the form of files. What is fragmentation? Different types of fragmentation?

- Fragmentation occurs in a dynamic memory allocation system when many of the free blocks are too small to satisfy any request. External Fragmentation: External Fragmentation happens when a dynamic memory allocation algorithm allocates some memory and a small piece is left over that cannot be effectively used. If too much external fragmentation occurs, the amount of usable memory is drastically reduced. Total memory space exists to satisfy a request, but it is not contiguous. Internal Fragmentation: Internal fragmentation is the space wasted inside of allocated memory blocks because of restriction on the allowed sizes of allocated blocks. Allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being used

What is DRAM? In which form does it store data? - DRAM is not the best, but its cheap, does the job, and is available almost everywhere you look. DRAM data resides in a cell made of a capacitor and a transistor. The capacitor tends to lose data unless its recharged every couple of milliseconds, and this recharging tends to slow down the performance of DRAM compared to speedier RAM types. What is Dispatcher? - Dispatcher module gives control of the CPU to the process selected by the short-term scheduler; this involves: Switching context, Switching to user mode, Jumping to the proper location in the user program to restart that program, dispatch latency time it takes for the dispatcher to stop one process and start another running. What is CPU Scheduler? - Selects from among the processes in memory that are ready to execute, and allocates the CPU to one of them. CPU scheduling decisions may take place when a process: 1.Switches from running to waiting state. 2.Switches from running to ready state. 3.Switches from waiting to ready. 4.Terminates. Scheduling under 1 and 4 is nonpreemptive. All other scheduling is preemptive. What is Context Switch? - Switching the CPU to another process requires saving the state of the old process and loading the saved state for the new process. This task is known as a context switch. Context-switch time is pure overhead, because the system does no useful work while switching. Its speed varies from machine to machine, depending on the memory speed, the number of registers which must be copied, the existed of special instructions(such as a single instruction to load or store all registers). What is cache memory? - Cache memory is random access memory (RAM) that a computer microprocessor can access more quickly than it can access regular RAM. As the microprocessor processes data, it looks first in the cache memory and if it finds the data there (from a previous reading of data), it does not have to do the more time-consuming reading of data from larger memory. What is a Safe State and what is its use in deadlock avoidance? - When a process requests an available resource, system must decide if immediate allocation leaves the system in a safe state. System is in safe state if there exists a safe sequence of all processes. Deadlock Avoidance: ensure that a system will never enter an unsafe state. What is a Real-Time System? - A real time process is a process that must respond to the events within a certain time period. A real time operating system is an operating system that can run real time processes successfully

Unix Interview Questions And Answers [Unix Frequently Asked


Questions ,Unix FAQ ]

How are devices represented in UNIX? All devices are represented by files called special files that are located in/dev directory. Thus, device files and other files are named and accessed in the same way. A 'regular file' is just an ordinary data file in the disk. A 'block special file' represents a device with characteristics similar to a disk (data transfer in terms of blocks). A 'character special file' represents a device with characteristics similar to a keyboard (data transfer is by stream of bits in sequential order). What is 'inode'? All UNIX files have its description stored in a structure called 'inode'. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers to the data blocks of the file. If the file is large, inode has indirect pointer to a block of pointers to additional data blocks (this further aggregates for larger files). A block is typically 8k. Inode consists of the following fields: File owner identifier File type File access permissions File access times Number of links File size Location of the file data Brief about the directory representation in UNIX A Unix directory is a file containing a correspondence between filenames and inodes. A directory is a special file that the kernel maintains. Only kernel modifies directories, but processes can read directories. The contents of a directory are a list of filename and inode number pairs. When new directories are created, kernel makes two entries named '.' (refers to the directory itself) and '..' (refers to parent directory). System call for creating directory is mkdir (pathname, mode). What are the Unix system calls for I/O? open(pathname,flag,mode) - open file creat(pathname,mode) - create file close(filedes) - close an open file read(filedes,buffer,bytes) - read data from an open file write(filedes,buffer,bytes) - write data to an open file lseek(filedes,offset,from) - position an open file dup(filedes) - duplicate an existing file descriptor dup2(oldfd,newfd) - duplicate to a desired file descriptor

fcntl(filedes,cmd,arg) - change properties of an open file ioctl(filedes,request,arg) - change the behaviour of an open file The difference between fcntl anf ioctl is that the former is intended for any open file, while the latter is for device-specific operations. How do you change File Access Permissions?

Every file has following attributes: owner's user ID ( 16 bit integer ) owner's group ID ( 16 bit integer ) File access mode word 'r w x -r w x- r w x' (user permission-group permission-others permission) r-read, w-write, x-execute To change the access mode, we use chmod(filename,mode). Example 1: To change mode of myfile to 'rw-rw-r--' (ie. read, write permission for user - read,write permission for group - only read permission for others) we give the args as: chmod(myfile,0664) . Each operation is represented by discrete values 'r' is 4 'w' is 2 'x' is 1 Therefore, for 'rw' the value is 6(4+2). Example 2: To change mode of myfile to 'rwxr--r--' we give the args as: chmod(myfile,0744). What are links and symbolic links in UNIX file system? A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers. Symbolic link 'is' a file that only contains the name of another file.Operation on the symbolic link is directed to the file pointed by the it.Both the limitations of links are eliminated in symbolic links. Commands for linking files are: Link ln filename1 filename2 Symbolic link ln -s filename1 filename2 What is a FIFO? FIFO are otherwise called as 'named pipes'. FIFO (first-in-first-out) is a special file which is said to be data transient. Once data is read from named pipe, it cannot be read again. Also, data can be read only in the order written. It is used in interprocess communication

where a process writes to one end of the pipe (producer) and the other reads from the other end (consumer). How do you create special files like named pipes and device files? The system call mknod creates special files in the following sequence. 1. kernel assigns new inode, 2. sets the file type to indicate that the file is a pipe, directory or special file, 3. If it is a device file, it makes the other entries like major, minor device numbers. For example: If the device is a disk, major device number refers to the disk controller and minor device number is the disk. Discuss the mount and unmount system calls The privileged mount system call is used to attach a file system to a directory of another file system; the unmount system call detaches a file system. When you mount another file system on to your directory, you are essentially splicing one directory tree onto a branch in another directory tree. The first argument to mount call is the mount point, that is , a directory in the current file naming system. The second argument is the file system to mount to that point. When you insert a cdrom to your unix system's drive, the file system in the cdrom automatically mounts to /dev/cdrom in your system. How does the inode map to data block of a file? Inode has 13 block addresses. The first 10 are direct block addresses of the first 10 data blocks in the file. The 11th address points to a one-level index block. The 12th address points to a two-level (double in-direction) index block. The 13th address points to a three-level(triple in-direction)index block. This provides a very large maximum file size with efficient access to large files, but also small files are accessed directly in one disk read.

Linux Interview Questions And Answers [Linux Frequently


Asked Questions ,Linux FAQ ] You need to see the last fifteen lines of the files dog, cat and horse. What command should you use? tail -15 dog cat horse The tail utility displays the end of a file. The -15 tells tail to display the last fifteen lines of each specified file. Who owns the data dictionary? The SYS user owns the data dictionary. The SYS and SYSTEM users are created when the database is created. You routinely compress old log files. You now need to examine a log from two months ago. In order to view its contents without first having to decompress it, use the _________ utility. zcat The zcat utility allows you to examine the contents of a compressed file much the same way that cat displays a file. You suspect that you have two commands with the same name as the command is not producing the expected results. What command can you use to determine the location of the command being run? which The which command searches your path until it finds a command that matches the command you are looking for and displays its full path. You locate a command in the /bin directory but do not know what it does. What command can you use to determine its purpose. whatis The whatis command displays a summary line from the man page for the specified command. You wish to create a link to the /data directory in bob's home directory so you issue the command ln /data /home/bob/datalink but the command fails. What option should you use in this command line to be successful. Use the -F option In order to create a link to a directory you must use the -F option. When you issue the command ls -l, the first character of the resulting display represents the file's ___________.

type The first character of the permission block designates the type of file that is being displayed. What utility can you use to show a dynamic listing of running processes? __________ top The top utility shows a listing of all running processes that is dynamically updated. Where is standard output usually directed? to the screen or display By default, your shell directs standard output to your screen or display. You wish to restore the file memo.ben which was backed up in the tarfile MyBackup.tar. What command should you type? tar xf MyBackup.tar memo.ben This command uses the x switch to extract a file. Here the file memo.ben will be restored from the tarfile MyBackup.tar. You need to view the contents of the tarfile called MyBackup.tar. What command would you use? tar tf MyBackup.tar The t switch tells tar to display the contents and the f modifier specifies which file to examine. You want to create a compressed backup of the users' home directories. What utility should you use? tar You can use the z modifier with tar to compress your archive at the same time as creating it. What daemon is responsible for tracking events on your system? syslogd The syslogd daemon is responsible for tracking system information and saving it to specified log files. You have a file called phonenos that is almost 4,000 lines long. What text filter can you use to split it into four pieces each 1,000 lines long? split

The split text filter will divide files into equally sized pieces. The default length of each piece is 1,000 lines. You would like to temporarily change your command line editor to be vi. What command should you type to change it? set -o vi The set command is used to assign environment variables. In this case, you are instructing your shell to assign vi as your command line editor. However, once you log off and log back in you will return to the previously defined command line editor. What account is created when you install Linux? root Whenever you install Linux, only one user account is created. This is the superuser account also known as root. What command should you use to check the number of files and disk space used and each user's defined quotas? repquota The repquota command is used to get a report on the status of the quotas you have set including the amount of allocated space and amount of used space. In order to run fsck on the root partition, the root partition must be mounted as readonly You cannot run fsck on a partition that is mounted as read-write. In order to improve your system's security you decide to implement shadow passwords. What command should you use? pwconv The pwconv command creates the file /etc/shadow and changes all passwords to 'x' in the /etc/passwd file. Bob Armstrong, who has a username of boba, calls to tell you he forgot his password. What command should you use to reset his command? passwd boba The passwd command is used to change your password. If you do not specify a username, your password will be changed.

The top utility can be used to change the priority of a running process? Another utility that can also be used to change priority is ___________? nice Both the top and nice utilities provide the capability to change the priority of a running process. What command should you type to see all the files with an extension of 'mem' listed in reverse alphabetical order in the /home/ben/memos directory. ls -r /home/ben/memos/*.mem The -c option used with ls results in the files being listed in chronological order. You can use wildcards with the ls command to specify a pattern of filenames. What file defines the levels of messages written to system log files? kernel.h To determine the various levels of messages that are defined on your system, examine the kernel.h file. What command is used to remove the password assigned to a group? gpasswd -r The gpasswd command is used to change the password assigned to a group. Use the -r option to remove the password from the group. What command would you type to use the cpio to create a backup called backup.cpio of all the users' home directories? find /home | cpio -o > backup.cpio The find command is used to create a list of the files and directories contained in home. This list is then piped to the cpio utility as a list of files to include and the output is saved to a file called backup.cpio. What can you type at a command line to determine which shell you are using? echo $SHELL The name and path to the shell you are using is saved to the SHELL environment variable. You can then use the echo command to print out the value of any variable by preceding the variable's name with $. Therefore, typing echo $SHELL will display the name of your shell. What type of local file server can you use to provide the distribution installation materials to the new machine during a network installation? A) Inetd B) FSSTND

C) DNS D) NNTP E) NFS E - You can use an NFS server to provide the distribution installation materials to the machine on which you are performing the installation. Answers a, b, c, and d are all valid items but none of them are file servers. Inetd is the superdaemon which controls all intermittently used network services. The FSSTND is the Linux File System Standard. DNS provides domain name resolution, and NNTP is the transfer protocol for usenet news. If you type the command cat dog & > cat what would you see on your display? Choose one: a. Any error messages only. b. The contents of the file dog. c. The contents of the file dog and any error messages. d. Nothing as all output is saved to the file cat. d When you use & > for redirection, it redirects both the standard output and standard error. The output would be saved to the file cat. You are covering for another system administrator and one of the users asks you to restore a file for him. You locate the correct tarfile by checking the backup log but do not know how the directory structure was stored. What command can you use to determine this? Choose one: a. tar fx tarfile dirname b. tar tvf tarfile filename c. tar ctf tarfile d. tar tvf tarfile d The t switch will list the files contained in the tarfile. Using the v modifier will display the stored directory structure. You have the /var directory on its own partition. You have run out of space. What should you do? Choose one: a. Reconfigure your system to not write to the log files. b. Use fips to enlarge the partition. c. Delete all the log files. d. Delete the partition and recreate it with a larger size. d

The only way to enlarge a partition is to delete it and recreate it. You will then have to restore the necessary files from backup. You have a new application on a CD-ROM that you wish to install. What should your first step be? Choose one: a. Read the installation instructions on the CD-ROM. b. Use the mount command to mount your CD-ROM as read-write. c. Use the umount command to access your CD-ROM. d. Use the mount command to mount your CD-ROM as read-only. d Before you can read any of the files contained on the CD-ROM, you must first mount the CD-ROM. When you create a new partition, you need to designate its size by defining the starting and ending _____________. cylinders When creating a new partition you must first specify its starting cylinder. You can then either specify its size or the ending cylinder. What key combination can you press to suspend a running job and place it in the background? ctrl-z Using ctrl-z will suspend a job and put it in the background. The easiest, most basic form of backing up a file is to _____ it to another location. copy The easiest most basic form of backing up a file is to make a copy of that file to another location such as a floppy disk. What type of server is used to remotely assign IP addresses to machines during the installation process? A) SMB B) NFS C) DHCP D) FT E) HTTP C - You can use a DHCP server to assign IP addresses to individual machines during the installation process. Answers a, b, d, and e list legitimate Linux servers, but these servers do not provide IP addresses. The SMB, or Samba, tool is used for file and print sharing

across multi-OS networks. An NFS server is for file sharing across Linux net-works. FTP is a file storage server that allows people to browse and retrieve information by logging in to it, and HTTP is for the Web. Which password package should you install to ensure that the central password file couldn't be stolen easily? A) PAM B) tcp_wrappers C) shadow D) securepass E) ssh C - The shadow password package moves the central password file to a more secure location. Answers a, b, and e all point to valid packages, but none of these places the password file in a more secure location. Answer d points to an invalid package. When using useradd to create a new user account, which of the following tasks is not done automatically. Choose one: a. Assign a UID. b. Assign a default shell. c. Create the user's home directory. d. Define the user's home directory. c The useradd command will use the system default for the user's home directory. The home directory is not created, however, unless you use the -m option. You want to enter a series of commands from the command-line. What would be the quickest way to do this? Choose One a. Press enter after entering each command and its arguments b. Put them in a script and execute the script c. Separate each command with a semi-colon (;) and press enter after the last command d. Separate each command with a / and press enter after the last command c The semi-colon may be used to tell the shell that you are entering multiple commands that should be executed serially. If these were commands that you would frequently want to run, then a script might be more efficient. However, to run these commands only once, enter the commands directly at the command line.

You attempt to use shadow passwords but are unsuccessful. What characteristic of the /etc/passwd file may cause this? Choose one: a. The login command is missing. b. The username is too long. c. The password field is blank. d. The password field is prefaced by an asterisk. c The password field must not be blank before converting to shadow passwords. When you install a new application, documentation on that application is also usually installed. Where would you look for the documentation after installing an application called MyApp? Choose one: a. /usr/MyApp b. /lib/doc/MyApp c. /usr/doc/MyApp d. In the same directory where the application is installed. c The default location for application documentation is in a directory named for the application in the /usr/doc directory. What file would you edit in your home directory to change which window manager you want to use? A) Xinit B) .xinitrc C) XF86Setup D) xstart E) xf86init Answer: B - The ~/.xinitrc file allows you to set which window man-ager you want to use when logging in to X from that account. Answers a, d, and e are all invalid files. Answer c is the main X server configuration file. What command allows you to set a processor-intensive job to use less CPU time? A) ps B) nice C) chps D) less E) more Answer: B - The nice command is used to change a job's priority level, so that it runs

slower or faster. Answers a, d, and e are valid commands but are not used to change process information. Answer c is an invalid command. While logged on as a regular user, your boss calls up and wants you to create a new user account immediately. How can you do this without first having to close your work, log off and logon as root? Choose one: a. Issue the command rootlog. b. Issue the command su and type exit when finished. c. Issue the command su and type logoff when finished. d. Issue the command logon root and type exit when finished. Answer: b You can use the su command to imitate any user including root. You will be prompted for the password for the root account. Once you have provided it you are logged in as root and can do any administrative duties. There are seven fields in the /etc/passwd file. Which of the following lists all the fields in the correct order? Choose one: a. username, UID, GID, home directory, command, comment b. username, UID, GID, comment, home directory, command c. UID, username, GID, home directory, comment, command d. username, UID, group name, GID, home directory, comment Answer: b The seven fields required for each line in the /etc/passwd file are username, UID, GID, comment, home directory, command. Each of these fields must be separated by a colon even if they are empty. Which of the following commands will show a list of the files in your home directory including hidden files and the contents of all subdirectories? Choose one: a. ls -c home b. ls -aR /home/username c. ls -aF /home/username d. ls -l /home/username Answer: b The ls command is used to display a listing of files. The -a option will cause hidden files to be displayed as well. The -R option causes ls to recurse down the directory tree. All of this starts at your home directory. In order to prevent a user from logging in, you can add a(n) ________at the beginning of the password field. Answer: asterick

If you add an asterick at the beginning of the password field in the /etc/passwd file, that user will not be able to log in. You have a directory called /home/ben/memos and want to move it to /home/bob/memos so you issue the command mv /home/ben/memos /home/bob. What is the results of this action? Choose one: a. The files contained in /home/ben/memos are moved to the directory /home/bob/memos/memos. b. The files contained in /home/ben/memos are moved to the directory /home/bob/memos. c. The files contained in /home/ben/memos are moved to the directory /home/bob/. d. The command fails since a directory called memos already exists in the target directory. Answer: a When using the mv command to move a directory, if a directory of the same name exists then a subdirectory is created for the files to be moved. Which of the following tasks is not necessary when creating a new user by editing the /etc/passwd file? Choose one: a. Create a link from the user's home directory to the shell the user will use. b. Create the user's home directory c. Use the passwd command to assign a password to the account. d. Add the user to the specified group. Answer: a There is no need to link the user's home directory to the shell command. Rather, the specified shell must be present on your system. You issue the following command useradd -m bobm But the user cannot logon. What is the problem? Choose one: a. You need to assign a password to bobm's account using the passwd command. b. You need to create bobm's home directory and set the appropriate permissions. c. You need to edit the /etc/passwd file and assign a shell for bobm's account. d. The username must be at least five characters long. Answer: a The useradd command does not assign a password to newly created accounts. You will still need to use the passwd command to assign a password. You wish to print the file vacations with 60 lines to a page. Which of the following commands will accomplish this? Choose one: a. pr -l60 vacations | lpr

b. pr -f vacations | lpr c. pr -m vacations | lpr d. pr -l vacations | lpr Answer: a The default page length when using pr is 66 lines. The -l option is used to specify a different length. Which file defines all users on your system? Choose one: a. /etc/passwd b. /etc/users c. /etc/password d. /etc/user.conf Answer: a The /etc/passwd file contains all the information on users who may log into your system. If a user account is not contained in this file, then the user cannot log in. Which two commands can you use to delete directories? A) rm B) rm -rf C) rmdir D) rd E) rd -rf Answer(s): B, C - You can use rmdir or rm -rf to delete a directory. Answer a is incorrect, because the rm command without any specific flags will not delete a directory, it will only delete files. Answers d and e point to a non-existent command. Which partitioning tool is available in all distributions? A) Disk Druid B) fdisk C) Partition Magic D) FAT32 E) System Commander Answer(s): B - The fdisk partitioning tool is available in all Linux distributions. Answers a, c, and e all handle partitioning, but do not come with all distributions. Disk Druid is made by Red Hat and used in its distribution along with some derivatives. Partition Magic and System Commander are tools made by third-party companies. Answer d is not a tool, but a file system type. Specifically, FAT32 is the file system type used in Windows 98. Which partitions might you create on the mail server's hard drive(s) other than the root, swap, and boot partitions?

[Choose all correct answers] A) /var/spool B) /tmp C) /proc D) /bin E) /home Answer(s): A, B, E - Separating /var/spool onto its own partition helps to ensure that if something goes wrong with the mail server or spool, the output cannot overrun the file system. Putting /tmp on its own partition prevents either software or user items in the /tmp directory from overrunning the file system. Placing /home off on its own is mostly useful for system re-installs or upgrades, allowing you to not have to wipe the /home hierarchy along with other areas. Answers c and d are not possible, as the /proc portion of the file system is virtual-held in RAM-not placed on the hard drives, and the /bin hierarchy is necessary for basic system functionality and, therefore, not one that you can place on a different partition. When planning your backup strategy you need to consider how often you will perform a backup, how much time the backup takes and what media you will use. What other factor must you consider when planning your backup strategy? _________ what to backup Choosing which files to backup is the first step in planning your backup strategy. What utility can you use to automate rotation of logs? Answer: logrotate The logrotate command can be used to automate the rotation of various logs. In order to display the last five commands you have entered using the history command, you would type ___________ . Answer: history 5 The history command displays the commands you have previously entered. By passing it an argument of 5, only the last five commands will be displayed. What command can you use to review boot messages? Answer: dmesg The dmesg command displays the system messages contained in the kernel ring buffer. By using this command immediately after booting your computer, you will see the boot messages. What is the minimum number of partitions you need to install Linux? Answer: 2 Linux can be installed on two partitions, one as / which will contain all files and a swap partition.

What is the name and path of the main system log? Answer: /var/log/messages By default, the main system log is /var/log/messages. Of the following technologies, which is considered a client-side script? A) JavaScript B) Java C) ASP D) C++ Answer: A - JavaScript is the only client-side script listed. Java and C++ are complete programming languages. Active Server Pages are parsed on the server with the results being sent to the client in HTML

Networking Interview Questions And Answers [Networking


Frequently Asked Questions ,Networking Server FAQ ] What is an Object server? With an object server, the Client/Server application is written as a set of communicating objects. Client object communicate with server objects using an Object Request Broker (ORB). The client invokes a method on a remote object. The ORB locates an instance of that object server class, invokes the requested method and returns the results to the client object. Server objects must provide support for concurrency and sharing. The ORB brings it all together. What is a Transaction server? With a transaction server, the client invokes remote procedures that reside on the server with an SQL database engine. These remote procedures on the server execute a group of SQL statements. The network exchange consists of a single request/reply message. The SQL statements either all succeed or fail as a unit. What is a Database Server? With a database server, the client passes SQL requests as messages to the database server. The results of each SQL command are returned over the network. The server uses its own processing power to find the request data instead of passing all the records back to the client and then getting it find its own data. The result is a much more efficient use of distributed processing power. It is also known as SQL engine. What are the most typical functional units of the Client/Server applications? User interface Business Logic and Shared data. What are all the Extended services provided by the OS?

Ubiquitous communications Network OS extension Binary large objects (BLOBs) Global directories and Network yellow pages Authentication and Authorization services System management Network time Database and transaction services Internet services Object- oriented services What are Triggers and Rules? Triggers are special user defined actions usually in the form of stored procedures, that are

automatically invoked by the server based on data related events. It can perform complex actions and can use the full power of procedural languages. A rule is a special type of trigger that is used to perform simple checks on data. What is meant by Transparency? Transparency really means hiding the network and its servers from the users and even the application programmers. What are TP-Lite and TP-Heavy Monitors? TP-Lite is simply the integration of TP Monitor functions in the database engines. TPHeavy are TP Monitors which supports the Client/Server architecture and allow PC to initiate some very complex multiserver transaction from the desktop. What are the two types of OLTP? TP lite, based on stored procedures. TP heavy, based on the TP monitors. What is a Web server? This new model of Client/Server consists of thin, protable, "universal" clients that talk to superfat servers. In the simplet form, a web server returns documents when clients ask for them by name. The clients and server communicate using an RPC-like protocol called HTTP. What are Super servers? These are fully-loaded machines which includes multiprocessors, high-speed disk arrays for intervive I/O and fault tolerant features. What is a TP Monitor? There is no commonly accepted definition for a TP monitor. According to Jeri Edwards' a TP Monitor is "an OS for transaction processing". TP Monitor does mainly two things extremely well. They are Process management and Transaction management.? They were originally introduced to run classes of applications that could service hundreds and sometimes thousands of clients. TP Monitors provide an OS - on top of existing OS that connects in real time these thousands of humans with a pool of shared server processes. What is meant by Asymmetrical protocols? There is a many-to-one relationship between clients and server. Clients always initiate the dialog by requesting a service. Servers are passively awaiting for requests from clients. What are the types of Transparencies? The types of transparencies the NOS middleware is expected to provide are:Location transparency Namespace transparency Logon transparency

Replication transparency Local/Remote access transparency Distributed time transparency Failure transparency and Administration transparency. What is the difference between trigger and rule? The triggers are called implicitly by database generated events, while stored procedures are called explicitly by client applications. What are called Transactions? The grouped SQL statements are called Transactions (or) A transaction is a collection of actions embused with ACID properties. What are the building blocks of Client/Server? The client The server and Middleware. Explain the building blocks of Client/Server? The client side building block runs the client side of the application. The server side building block runs the server side of the application. The middleware buliding block runs on both the client and server sides of an application. It is broken into three categories:-

Transport stack Network OS Service-specific middleware. What are all the Base services provided by the OS? Task preemption Task priority Semaphores Interprocess communications (IPC) Local/Remote Interprocess communication Threads Intertask protection Multiuser High performance file system Efficient memory management and Dynamically linked Run-time extensions.

What are the roles of SQL? SQL is an interactive query language for ad hoc database queries. SQL is a database programming language. SQL is a data definition and data administration language. SQL is the language of networked database servers SQL helps protect the data in a multi-user networked environment. Because of these multifacted roles it plays, physicists might call SQL as "The grand unified theory of database". What are the characteristics of Client/Server? Service Shared resources Asymmentrical protocols Transparency of location Mix-and-match Message based exchanges Encapsulation of services Scalability Integrity Client/Server computing is the ultimate "Open platform". It gives the freedom to mixand-match components of almost any level. Clients and servers are loosely coupled systems that interact through a message-passing mechanism. What is Structured Query Langauge (SQL)? SQL is a powerful set-oriented language which was developed by IBM research for the databases that adhere to the relational model. It consists of a short list of powerful, yet highly flexible, commands that can be used to manipulate information collected in tables. Through SQL, we can manipulate and control sets of records at a time. What is Remote Procedure Call (RPC)? RPC hides the intricacies of the network by using the ordinary procedure call mechanism familiar to every programmer. A client process calls a function on a remote server and suspends itself until it gets back the results. Parameters are passed like in any ordinary procedure. The RPC, like an ordinary procedure, is synchoronous. The process that issues the call waits until it gets the results. Under the covers, the RPC run-time software collects values for the parameters, forms a message, and sends it to the remote server. The server receives the request, unpack the parameters, calls the procedures, and sends the reply back to the client. It is a telephonelike metaphor. What are the main components of Transaction-based Systems? Resource Manager Transaction Manager and Application Program.

What are the three types of SQL database server architecture? Process-per-client Architecture. (Example: Oracle 6, Informix ) Multithreaded Architecture. (Example: Sybase, SQL server) Hybrid Architecture What are the Classification of clients? Non-GUI clients - Two types are:Non-GUI clients that do not need multi-tasking (Example: Automatic Teller Machines (ATM), Cell phone) Non-GUI clients that need multi-tasking (Example: ROBOTs) GUI clients OOUI clients What are called Non-GUI clients, GUI Clients and OOUI Clients? Non-GUI Client: These are applications, generate server requests with a minimal amount of human interaction. GUI Clients: These are applicatoins, where occassional requests to the server result from a human interacting with a GUI (Example: Windows 3.x, NT 3.5) OOUI clients : These are applications, which are highly-iconic, object-oriented user interface that provides seamless access to information in very visual formats. (Example: MAC OS, Windows 95, NT 4.0) What is Message Oriented Middleware (MOM)? MOM allows general purpose messages to be exchanged in a Client/Server system using message queues. Applications communicate over networks by simply putting messages in the queues and getting messages from queues. It typically provides a very simple high level APIs to its services. MOM's messaging and queuing allow clients and servers to communicate across a network without being linked by a private, dedicated, logical connection. The clients and server can run at different times. It is a post-office like metaphor. What is meant by Middleware? Middleware is a distributed software needed to support interaction between clients and servers. In short, it is the software that is in the middle of the Client/Server systems and it acts as a bridge between the clients and servers. It starts with the API set on the client side that is used to invoke a service and it covers the transmission of the request over the network and the resulting response. It neither includes the software that provides the actual service - that is in the servers domain nor the user interface or the application login - that's in clients domain. What are the functions of the typical server program? It waits for client-initiated requests. Executes many requests at the same time. Takes care

of VIP clients first. Initiates and runs background task activity. Keeps running. Grown bigger and faster. What is meant by Symmentric Multiprocessing (SMP)? It treats all processors as equal. Any processor can do the work of any other processor. Applications are divided into threads that can run concurrently on any available processor. Any processor in the pool can run the OS kernel and execute user-written threads. What are General Middleware? It includes the communication stacks, distributed directories, authentication services, network time, RPC, Queuing services along with the network OS extensions such as the distributed file and print services.

Perl Interview Questions And Answers [Perl Frequently Asked


Questions ,Perl FAQ ] Why do you use Perl? Perl is a powerful free interpreter. Perl is portable, flexible and easy to learn. How do I set environment variables in Perl programs? you can just do something like this: $path = $ENV{'PATH'}; As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables. Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path:: $ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/yourname/bin'; Which of these is a difference between C++ and Perl? Perl can have objects whose data cannot be accessed outside its class, but C++ cannot. Perl can use closures with unreachable private data as objects, and C++ doesn't support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object', allowing you do look all over the object. Perl doesn't have pointer arithmetic. It also doesn't allow `#define private public' to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe. How to open and read data files with Perl Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from. As an example, suppose you need to read some data from a file named "checkbook.txt". Here's a simple open statement that opens the checkbook file for read access: open (CHECKBOOK, "checkbook.txt"); In this example, the name "CHECKBOOK" is the file handle that you'll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named "CHECKBOOK". Now that we've opened the checkbook file, we'd like to be able to read what's in it. Here's how to read one line of data from the checkbook file: $record = < CHECKBOOK > ; After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The "<>" symbol is called the line reading operator. To print every record of information from the checkbook file open (CHECKBOOK, "checkbook.txt") || die "couldn't open the file!"; while ($record = < CHECKBOOK >) { print $record; } close(CHECKBOOK);

How do I do fill_in_the_blank for each file in a directory? Here's code that just prints a listing of every file in the current directory: #!/usr/bin/perl -w opendir(DIR, "."); @files = readdir(DIR); closedir(DIR); foreach $file (@files) { print "$file\n"; } How do I do fill_in_the_blank for each file in a directory?

Here's code that just prints a listing of every file in the current directory: #!/usr/bin/perl -w opendir(DIR, "."); @files = readdir(DIR); closedir(DIR); foreach $file (@files) { print "$file\n"; } How do I generate a list of all .html files in a directory? Here's a snippet of code that just prints a listing of every file in the current directory that ends with the extension .html: #!/usr/bin/perl -w opendir(DIR, "."); @files = grep(/\.html$/,readdir(DIR)); closedir(DIR); foreach $file (@files) { print "$file\n"; } What is Perl one-liner? There are two ways a Perl script can be run: --from a command line, called one-liner, that means you type and execute immediately on the command line. You'll need the -e option to start like "C:\ %gt perl -e "print \"Hello\";". One-liner doesn't mean one Perl statement. One-liner may contain many statements in one line. --from a script file, called Perl program. Assuming both a local($var) and a my($var) exist, what's the difference between ${var} and ${"var"}? ${var} is the lexical variable $var, and ${"var"} is the dynamic variable $var. Note that because the second is a symbol table lookup, it is disallowed under `use strict

"refs"'. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable. What happens when you return a reference to a private variable? Perl keeps track of your variables, whether dynamic or otherwise, and doesn't free things before you're done using them. How to turn on Perl warnings? Why is that important? Perl is very forgiving of strange and sometimes wrong code, which can mean hours spent searching for bugs and weird results. Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run. There are various ways of turning on Perl warnings: For Perl one-liner, use -w option on the command line. On Unix or Windows, use the -w option in the shebang line (The first # line in the script). Note: Windows Perl interpreter may not require it. For other systems, choose compiler warnings, or check compiler documentation. What are scalar data and scalar variables? Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\'s scalar in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more alphanumeric characters or underscores. It is case sensitive. Why should I use the -w argument with my Perl programs? Many Perl developers use the -w option of the interpreter, especially during the development stages of an application. This warning option turns on many warning messages that can help you understand and debug your applications. To use this option on Unix systems, just include it on the first line of the program, like this: #!/usr/bin/perl -w If you develop Perl apps on a DOS/Windows computer, and you're creating a program named myApp.pl, you can turn on the warning messages when you run your program like this: perl -w myApp.pl Assuming $_ contains HTML, which of the following substitutions will remove all tags in it? 1.s/<.*>//g; 2.s/<.*?>//gs; 3.s/<\/?[A-Z]\w*(?:\s+[A-Z]\w*(?:\s*=\s*(?:(["']).*?\1|[\w-.]+))?)*\s*>//gsix; You can't do that. If it weren't for HTML comments, improperly formatted HTML, and tags with interesting

data like < SCRIPT >, you could do this. Alas, you cannot. It takes a lot more smarts, and quite frankly, a real parser. I want users send data by formmail but when they send nothing or call it from web site they will see error. codes in PHP like this: if (isset($HTTP_POST_VARS)){ .......... } else{ echo ("error lalalalal") } How it will look in perl? In php it will be like if (isset($HTTP_POST_VARS)){ .... } In perl, tried this. if ($ENV{'REQUEST_METHOD'} eq 'POST'){ ..... } What is the output of the following Perl program? 1 $p1 = "prog1.java"; 2 $p1 =~ s/(.*)\.java/$1.cpp/; 3 print "$p1\n"; prog1.cpp Why aren't Perl's patterns regular expressions?

Because Perl patterns have backreferences. A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term. What does Perl do if you try to exploit the execve(2) race involving setuid scripts? Sends mail to root and exits. It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.

How do I do < fill-in-the-blank > for each element in a hash? Here's a simple technique to process each element in a hash: #!/usr/bin/perl -w %days = ( 'Sun' =>'Sunday', 'Mon' => 'Monday', 'Tue' => 'Tuesday', 'Wed' => 'Wednesday', 'Thu' => 'Thursday', 'Fri' => 'Friday', 'Sat' => 'Saturday' ); foreach $key (sort keys %days) { print "The long name for $key is $days{$key}.\n"; } How do I sort a hash by the hash key? Suppose we have a class of five students. Their names are kim, al, rocky, chrisy, and jane. Here's a test program that prints the contents of the grades hash, sorted by student name: #!/usr/bin/perl -w %grades = ( kim => 96, al => 63, rocky => 87, chrisy => 96, jane => 79, ); print "\n\tGRADES SORTED BY STUDENT NAME:\n"; foreach $key (sort (keys(%grades))) { print "\t\t$key \t\t$grades{$key}\n"; } The output of this program looks like this: GRADES SORTED BY STUDENT NAME: al 63 chrisy 96 jane 79

kim 96 rocky 87 } How do you print out the next line from a filehandle with all its bytes reversed? print scalar reverse scalar <FH> Surprisingly enough, you have to put both the reverse and the <FH> into scalar context separately for this to work. How do I send e-mail from a Perl/CGI program on a Unix system? Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We'll go through a quick example here. Assuming that you've already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message: # the rest of your program is up here ... open(MAIL, "|/usr/lib/sendmail -t"); print MAIL "To: $sendToAddress\n"; print MAIL "From: $myEmailAddress\n"; print MAIL "Subject: $subject\n"; print MAIL "This is the message body.\n"; print MAIL "Put your message here in the body.\n"; close (MAIL); How to read from a pipeline with Perl Example 1: To run the date command from a Perl program, and read the output of the command, all you need are a few lines of code like this: open(DATE, "date|"); $theDate = <DATE>; close(DATE); The open() function runs the external date command, then opens a file handle DATE to the output of the date command. Next, the output of the date command is read into the variable $theDate through the file handle DATE. Example 2: The following code runs the "ps -f" command, and reads the output:

open(PS_F, "ps -f|"); while (<PS_F>) { ($uid,$pid,$ppid,$restOfLine) = split; # do whatever I want with the variables here ... } close(PS_F); Why is it hard to call this function: sub y { "because" } Because y is a kind of quoting operator. The y/// operator is the sed-savvy synonym for tr///. That means y(3) would be like tr(), which would be looking for a second string, as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][AZ]. What does `$result = f() .. g()' really return? False so long as f() returns false, after which it returns true until g() returns true, and then starts the cycle again. This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()'. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don't want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this: $bingo = ( a() .. b() ) ... ( c() .. d() ); Why does Perl not have overloaded functions? Because you can inspect the argument count, return context, and object types all by yourself. In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions. What does read() return at end of file? 0 A defined (but false) 0 value is the proper indication of the end of file for read() and sysread(). What does `new $cur->{LINK}' do? (Assume the current package has no new() function of its own.) $cur->new()->{LINK} The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression. This is why `new $obj[23] arg' does't work, as well as why `print $fh[23] "stuff\n"' does't work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you'll not be surprised.

How do I sort a hash by the hash value? Here's a program that prints the contents of the grades hash, sorted numerically by the hash value: #!/usr/bin/perl -w # Help sort a hash by the hash 'value', not the 'key'. to highest). sub hashValueAscendingNum { $grades{$a} <=> $grades{$b}; }

# Help sort a hash by the hash 'value', not the 'key'. # Values are returned in descending numeric order # (highest to lowest). sub hashValueDescendingNum { $grades{$b} <=> $grades{$a}; }

%grades = ( student1 => 90, student2 => 75, student3 => 96, student4 => 55, student5 => 76, ); print "\n\tGRADES IN ASCENDING NUMERIC ORDER:\n"; foreach $key (sort hashValueAscendingNum (keys(%grades))) { print "\t\t$grades{$key} \t\t $key\n"; } print "\n\tGRADES IN DESCENDING NUMERIC ORDER:\n"; foreach $key (sort hashValueDescendingNum (keys(%grades))) { print "\t\t$grades{$key} \t\t $key\n"; } How to read file into hash array ? open(IN, "<name_file") or die "Couldn't open file for processing: $!"; while (<IN>) { chomp; $hash_table{$_} = 0;

} close IN; print "$_ = $hash_table{$_}\n" foreach keys %hash_table; How do you find the length of an array? $@array What value is returned by a lone `return;' statement? The undefined value in scalar context, and the empty list value () in list context. This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called. What's the difference between /^Foo/s and /^Foo/? The second would match Foo other than at the start of the record if $* were set. The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well -- just as they would if $* weren't set at all. Does Perl have reference type? Yes. Perl can make a scalar or hash type reference by using backslash operator. For example $str = "here we go"; # a scalar variable $strref = \$str; # a reference to a scalar @array = (1..10); # an array $arrayref = \@array; # a reference to an array Note that the reference itself is a scalar. How to dereference a reference? There are a number of ways to dereference a reference. Using two dollar signs to dereference a scalar. $original = $$strref; Using @ sign to dereference an array. @list = @$arrayref; Similar for hashes. What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash? 5 length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it's empty, otherwise it's a string representing the fullness of the buckets, like "18/32" or "39/64". The length of that string is likely to be 5. Likewise, `length(@a)' would be 2 if there were 37 elements in @a.

If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}? The second is disallowed under `use strict "refs"'. Dereferencing a string with *{"STR"} is disallowed under the refs stricture, although *{STR} would not be. This is similar in spirit to the way ${"STR"} is always the symbol table variable, while ${STR} may be the lexical variable. If it's not a bareword, you're playing with the symbol table in a particular dynamic fashion. How do I do < fill-in-the-blank > for each element in an array? #!/usr/bin/perl -w @homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth'); foreach (@homeRunHitters) { print "$_ hit a lot of home runs in one year\n"; } How do I replace every <TAB> character in a file with a comma? perl -pi.bak -e 's/\t/,/g' myfile.txt What is the easiest way to download the contents of a URL with Perl? Once you have the libwww-perl library, LWP.pm installed, the code is this: #!/usr/bin/perl use LWP::Simple; $url = get 'http://www.websitename.com/'; How to concatenate strings with Perl? Method #1 - using Perl's dot operator: $name = 'checkbook'; $filename = "/tmp/" . $name . ".tmp"; Method #2 - using Perl's join function $name = "checkbook"; $filename = join "", "/tmp/", $name, ".tmp"; Method #3 - usual way of concatenating strings $filename = "/tmp/${name}.tmp"; How do I read command-line arguments with Perl? With Perl, command-line arguments are stored in the array named @ARGV. $ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc. $#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1. Here's a simple program:

#!/usr/bin/perl $numArgs = $#ARGV + 1; print "thanks, you gave me $numArgs command-line arguments.\n"; foreach $argnum (0 .. $#ARGV) { print "$ARGV[$argnum]\n"; } When would `local $_' in a function ruin your day? When your caller was in the middle for a while(m//g) loop The /g state on a global variable is not protected by running local on it. That'll teach you to stop using locals. Too bad $_ can't be the target of a my() -- yet. What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }' ? Their destructors are called when that interpreter thread shuts down. When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code. Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements: $$ref; # returns a scalar $$ref[0]; # returns the first element of that array $ref- > [0]; # returns the first element of that array @$ref; # returns the contents of that array, or number of elements, in scalar context $&$ref; # returns the last index in that array $ref- > [0][5]; # returns the sixth element in the first row @{$ref- > {key}} # returns the contents of the array that is the value of the key "key"

How do you match one letter in the current locale? /[^\W_\d]/ We don't have full POSIX regexps, so you can't get at the isalpha() <ctype.h> macro save indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas, which is what you want. How do I print the entire contents of an array with Perl? To answer this question, we first need a sample array. Let's assume that you have an array that contains the name of baseball teams, like this: @teams = ('cubs', 'reds', 'yankees', 'dodgers'); If you just want to print the array with the array members separated by blank spaces, you can just print the array like this: @teams = ('cubs', 'reds', 'yankees', 'dodgers'); print "@teams\n"; But that's not usually the case. More often, you want each element printed on a separate line. To achieve this, you can use this code:

@teams = ('cubs', 'reds', 'yankees', 'dodgers'); foreach (@teams) { print "$_\n"; } Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical? They are not identical. There are several differences between using single quotes and double quotes for strings. 1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values. 2. The single-quoted string will print just like it is. It doesn't care the dollar signs. 3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc. 4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc. How many ways can we express string in Perl? Many. For example 'this is a string' can be expressed in: "this is a string" qq/this is a string like double-quoted string/ qq^this is a string like double-quoted string^ q/this is a string/ q&this is a string& q(this is a string) How do you give functions private variables that retain their values between calls? Create a scope surrounding that sub that contains lexicals. Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus: { my $i = 0; sub next_i { $i++ } sub last_i { --$i } } creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

S-ar putea să vă placă și