Programming the Network with Perl Concludes with Chapter 6, Mobile Agents, Which Explores an Area of Computer Networking That Is Generating Considerable Research

Total Page:16

File Type:pdf, Size:1020Kb

Programming the Network with Perl Concludes with Chapter 6, Mobile Agents, Which Explores an Area of Computer Networking That Is Generating Considerable Research Paul Barry Institute of Technology, Carlow, Ireland Copyright ©2002 John Wiley & Sons Ltd Baffins Lane, Chichester, West Sussex PO19 1UD, England National 01243 779777 International (+44) 1243 779777 e-mail (for orders and customer service enquiries): [email protected] Visit our Home Page on http://www.wileyeurope.com or http://www.wiley.com All Rights Reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except under the terms of the Copyright, Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London, UK W1P 0LP, without the permission in writing of the Publisher with the exception of any material supplied specifically for the purpose of being entered and executed on a computer system for exclusive use by the purchaser of the publication. Neither the author nor John Wiley & Sons, Ltd accept any responsibility or liability for loss or damage occasioned to any person or property through using the material, instructions, methods or ideas contained herein, or acting or refraining from acting as a result of such use. The author and publisher expressly disclaim all implied warranties, including mer- chantability or fitness for any particular purpose. There will be no duty on the author or publisher to correct any errors or defects in the software. Designations used by companies to distinguish their products are often claimed as trade- marks. In all instances where John Wiley & Sons, Ltd is aware of a claim, the product names appear in capital or all capital letters. Readers, however, should contact the appropriate companies for more complete information regarding trademarks and registration Library of Congress Cataloging-in-Publication Data (applied for) British Library Cataloguing in Publication Data A catalogue record for this book is available from the British Library ISBN 0 471 48670 1 Typeset in 9.5/12.5pt Lucida Bright by T&T Productions Ltd, London. Printed and bound in Great Britain by Biddles Ltd, Guildford and Kings Lynn. This book is printed on acid-free paper responsibly manufactured from sustainable forestry in which at least two trees are planted for each one used for paper production. Dedicated to Deirdre, for continuing to put her ambitions on hold while I pursue mine. Contents Preface xiii 1 Meet Perl 1 1.1 Perl’s Default Behaviour 1 1.1.1 Our first Perl program 2 1.1.2 Perl’s default variable 3 1.1.3 The strange first line explained 3 1.2 Using Variables in Perl 4 1.2.1 One of something: scalars 5 1.2.2 A collection of somethings: arrays and lists 6 1.2.3 Hashes 8 1.2.4 References 9 1.2.5 Built-in variables 12 1.2.6 Scoping with local, my and our 12 1.3 Controlling Flow 13 1.3.1 if 13 1.3.2 The ternary conditional operator 14 1.3.3 while 15 1.3.4 for 15 1.3.5 unless 16 1.3.6 until 16 1.3.7 foreach 16 1.3.8 do 17 1.3.9 eval 17 1.3.10 Statement modifiers 18 1.4 Boolean in Perl 19 1.5 Perl Operators 20 1.6 Subroutines 21 1.6.1 Processing parameters 21 1.6.2 Returning results 22 1.6.3 I want an array 23 1.6.4 In-built subroutines 23 1.6.5 References to subroutines 26 1.7 Perl I/O 26 1.7.1 Variable interpolation 28 1.8 Packages, Modules and Objects 29 1.8.1 Modules 30 1.8.2 Objects 30 1.8.3 The joy of CPAN 31 1.9 More Perl 32 1.10 Where To From Here? 32 viii Contents 1.11 Print Resources 32 1.12 Web Resources 33 2 Snooping 35 2.1 Thank You, Tim Potter 36 2.2 Preparing To Snoop 37 2.2.1 Installing NetPacket::* 37 2.2.2 Installing Net::Pcap 38 2.2.3 Installing Net::PcapUtils 39 2.2.4 Online documentation 39 2.2.5 Configuring your network interface 40 2.3 Building Low-Level Snooping Tools 41 2.3.1 loop = open + next 42 2.3.2 Optional parameters: loop and open 43 2.3.3 Optional parameters: the callback function 45 2.3.4 Ethernet Analysis 45 2.3.5 EtherSnooper (v0.01) 48 2.3.6 EtherSnooper (v0.02) 52 2.3.7 EtherSnooper (v0.03) 55 2.3.8 Displaying IP addresses 58 2.4 Snooping IP Datagrams 63 2.4.1 EtherSnooper (v0.05) 64 2.4.2 EtherSnooper (v0.06) 67 2.5 Transport Snoopers 69 2.5.1 Preparing to snoop UDP 70 2.5.2 Preparing to snoop TCP 70 2.5.3 The TCP and UDP gotcha! 71 2.5.4 Application traffic monitoring 75 2.5.5 EtherSnooper (v0.07) 81 2.6 The Network Debugger 83 2.6.1 Processing command-line parameters 85 2.6.2 Storing captured results 85 2.6.3 The NetDebug source code 86 2.7 Where To From Here? 95 2.8 Print Resources 95 2.9 Web Resources 96 3 Sockets 99 3.1 Clients and Servers 99 3.1.1 Client characteristics 100 3.1.2 Server characteristics 101 3.2 Transport Services 101 3.2.1 Unreliable transport 102 3.2.2 Reliable transport 103 3.3 Introducing the Perl Socket API 104 3.4 Socket Support Subroutines 105 3.4.1 inet_aton and inet_ntoa 105 3.4.2 Socket addresses 105 3.4.3 getservbyname and getservbyport 106 3.4.4 getprotobyname and getprotobynumber 106 3.4.5 gethostbyname and gethostbyaddr 107 3.5 Simple UDP Clients and Servers 108 3.5.1 Testing with localhost 108 3.5.2 The first UDP server 108 3.5.3 The first UDP client 111 Contents ix 3.6 Genericity and Robustness 112 3.7 UDP Is Unreliable 116 3.7.1 No flow control 117 3.8 Sending and Receiving with UDP 118 3.9 Dealing with Deadlock 120 3.9.1 Specifying a time-out 121 3.9.2 Checking for data 123 3.9.3 Spawning a subprocess 125 3.10 TCP Clients and Servers 130 3.10.1 The first TCP server 131 3.10.2 The first TCP client 134 3.11 A Common TCP Gotcha 140 3.12 More TCP Socket Communication 143 3.12.1 The remote syntax checker server 144 3.12.2 The remote syntax checker client 147 3.13 The Concurrent Syntax Checker 150 3.14 Object-Oriented Sockets 153 3.14.1 IO::Socket 154 3.14.2 IO::Socket::INET 154 3.14.3 An object-oriented client and server 156 3.15 Where To From Here? 158 3.16 Print Resources Y 158 3.17 Web Resources L 159 4 ProtocolsF 161 4.1 Gotcha! 161 4.1.1 What’s the deal with newline?M 162 4.2 Working with the Web 164 4.2.1 HTTP requests and responsesA 164 4.3 The World’s Worst Web Browser 165 4.3.1 Embedded graphicsE 168 4.3.2 A persistent wwwb 169 4.3.3 A better get_resource T 172 4.4 HTTP Status Codes 174 4.5 It’s the Gisle and Graham Show! 178 4.5.1 Getting libwww-perl and libnet 179 4.6 The Library for WWW Access in Perl 180 4.6.1 The libwww-perl classes 181 4.7 The LWPwwwb Program 181 4.8 Doing More with LWPwwwb 184 4.8.1 Parsing HTML 185 4.8.2 Some parsewwwb examples 187 4.8.3 The HTML::Parser examples 189 4.9 Building a Custom Web Server 190 4.9.1 The custom Web server source code 190 4.9.2 The custom Web server in action 196 4.10 The libnet Library 197 4.10.1 Working with Usenet 198 4.10.2 The news reading source code 199 4.11 Email Enabling simplehttpd 205 4.11.1 The simple mail transfer protocol 205 4.11.2 The Net::SMTP module 210 4.11.3 Creating simplehttp2d 211 Team-Fly® x Contents 4.12 Other Networking Add-On Modules 213 4.12.1 Installing Net::Telnet 213 4.12.2 A Net::Telnet example 214 4.13 Where To From Here? 217 4.14 Print Resources 217 4.15 Web Resources 217 5 Management 221 5.1 Simple Management with ICMP 222 5.2 Doing the Ping Thing 222 5.2.1 Some ping examples 223 5.3 Doing the Net::Ping Thing 225 5.4 Tracing Routes 227 5.4.1 How traceroute works 228 5.5 Not So Simple Management with SNMP 229 5.5.1 A little SNMP history 229 5.6 The SNMP Management Framework 230 5.7 Managed Data 231 5.7.1 The TCP/IP MIB 231 5.8 The SNMP Protocol 235 5.8.1 SNMP’s operational model 235 5.8.2 A brief tour of SNMPv1, SNMPv2 and SNMPv3 235 5.8.3 SNMP communities 237 5.9 The Net::SNMP Module 237 5.9.1 The Net::SNMP methods 238 5.10 Working With Net::SNMP 240 5.10.1 Working with mnemonic object identifiers 242 5.10.2 The udpstats source code 243 5.10.3 The howlongup program 247 5.11 What’s Up? 249 5.11.1 Being more careful 254 5.12 Setting MIB-II Data 256 5.13 IP Router Mapping 258 5.14 Where To From Here? 266 5.15 Print Resources 266 5.16 Web Resources 267 6 Mobile Agents 269 6.1 What is a Mobile Agent? 269 6.1.1 Mobile agent = code + state 270 6.1.2 What is a mobile-agent environment? 270 6.2 Mobile-Agent Examples 270 6.2.1 Revisiting multiwho 270 6.2.2 Revisiting ipdetermine 271 6.3 Mobile-Agent Advantages/Disadvantages 272 6.4 Perl Agents 274 6.4.1 Preparing Perl for mobile agents 274 6.5 The Agent.pm Module 275 6.6 Ooooh, Objects! 276 6.7 The Default Mobile Agent 276 6.8 A Launching Mobile-Agent Environment 280 6.9 A One-Shot Location 282 Contents xi 6.10 Relocating To Multiple Locations 284 6.10.1 Processing multiple mobile agents 285 6.10.2 Identifying multiple locations 285 6.10.3 A multi-location mobile agent 287 6.11 The Mobile-Agent multiwho 292 6.12 The Mobile-Agent ipdetermine 293 6.13 The Cloning Mobile-Agent ipdetermine 297 6.14 Other Perl Agent Examples 304 6.15 Where To From Here? 305 6.16 Print Resources 305 6.17 Web Resources 305 Appendix A.
Recommended publications
  • X10 Language Specification
    X10 Language Specification Version 2.6.2 Vijay Saraswat, Bard Bloom, Igor Peshansky, Olivier Tardieu, and David Grove Please send comments to [email protected] January 4, 2019 This report provides a description of the programming language X10. X10 is a class- based object-oriented programming language designed for high-performance, high- productivity computing on high-end computers supporting ≈ 105 hardware threads and ≈ 1015 operations per second. X10 is based on state-of-the-art object-oriented programming languages and deviates from them only as necessary to support its design goals. The language is intended to have a simple and clear semantics and be readily accessible to mainstream OO pro- grammers. It is intended to support a wide variety of concurrent programming idioms. The X10 design team consists of David Grove, Ben Herta, Louis Mandel, Josh Milthorpe, Vijay Saraswat, Avraham Shinnar, Mikio Takeuchi, Olivier Tardieu. Past members include Shivali Agarwal, Bowen Alpern, David Bacon, Raj Barik, Ganesh Bikshandi, Bob Blainey, Bard Bloom, Philippe Charles, Perry Cheng, David Cun- ningham, Christopher Donawa, Julian Dolby, Kemal Ebcioglu,˘ Stephen Fink, Robert Fuhrer, Patrick Gallop, Christian Grothoff, Hiroshi Horii, Kiyokuni Kawachiya, Al- lan Kielstra, Sreedhar Kodali, Sriram Krishnamoorthy, Yan Li, Bruce Lucas, Yuki Makino, Nathaniel Nystrom, Igor Peshansky, Vivek Sarkar, Armando Solar-Lezama, S. Alexander Spoon, Toshio Suganuma, Sayantan Sur, Toyotaro Suzumura, Christoph von Praun, Leena Unnikrishnan, Pradeep Varma, Krishna Nandivada Venkata, Jan Vitek, Hai Chuan Wang, Tong Wen, Salikh Zakirov, and Yoav Zibin. For extended discussions and support we would like to thank: Gheorghe Almasi, Robert Blackmore, Rob O’Callahan, Calin Cascaval, Norman Cohen, Elmootaz El- nozahy, John Field, Kevin Gildea, Sara Salem Hamouda, Michihiro Horie, Arun Iyen- gar, Chulho Kim, Orren Krieger, Doug Lea, John McCalpin, Paul McKenney, Hiroki Murata, Andrew Myers, Filip Pizlo, Ram Rajamony, R.
    [Show full text]
  • Exploring Languages with Interpreters and Functional Programming Chapter 22
    Exploring Languages with Interpreters and Functional Programming Chapter 22 H. Conrad Cunningham 5 November 2018 Contents 22 Overloading and Type Classes 2 22.1 Chapter Introduction . .2 22.2 Polymorphism in Haskell . .2 22.3 Why Overloading? . .2 22.4 Defining an Equality Class and Its Instances . .4 22.5 Type Class Laws . .5 22.6 Another Example Class Visible ..................5 22.7 Class Extension (Inheritance) . .6 22.8 Multiple Constraints . .7 22.9 Built-In Haskell Classes . .8 22.10Comparison to Other Languages . .8 22.11What Next? . .9 22.12Exercises . 10 22.13Acknowledgements . 10 22.14References . 11 22.15Terms and Concepts . 11 Copyright (C) 2017, 2018, H. Conrad Cunningham Professor of Computer and Information Science University of Mississippi 211 Weir Hall P.O. Box 1848 University, MS 38677 (662) 915-5358 Browser Advisory: The HTML version of this textbook requires use of a browser that supports the display of MathML. A good choice as of November 2018 is a recent version of Firefox from Mozilla. 1 22 Overloading and Type Classes 22.1 Chapter Introduction Chapter 5 introduced the concept of overloading. Chapters 13 and 21 introduced the related concepts of type classes and instances. The goal of this chapter and the next chapter is to explore these concepts in more detail. The concept of type class was introduced into Haskell to handle the problem of comparisons, but it has had a broader and more profound impact upon the development of the language than its original purpose. This Haskell feature has also had a significant impact upon the design of subsequent languages (e.g.
    [Show full text]
  • On the Interaction of Object-Oriented Design Patterns and Programming
    On the Interaction of Object-Oriented Design Patterns and Programming Languages Gerald Baumgartner∗ Konstantin L¨aufer∗∗ Vincent F. Russo∗∗∗ ∗ Department of Computer and Information Science The Ohio State University 395 Dreese Lab., 2015 Neil Ave. Columbus, OH 43210–1277, USA [email protected] ∗∗ Department of Mathematical and Computer Sciences Loyola University Chicago 6525 N. Sheridan Rd. Chicago, IL 60626, USA [email protected] ∗∗∗ Lycos, Inc. 400–2 Totten Pond Rd. Waltham, MA 02154, USA [email protected] February 29, 1996 Abstract Design patterns are distilled from many real systems to catalog common programming practice. However, some object-oriented design patterns are distorted or overly complicated because of the lack of supporting programming language constructs or mechanisms. For this paper, we have analyzed several published design patterns looking for idiomatic ways of working around constraints of the implemen- tation language. From this analysis, we lay a groundwork of general-purpose language constructs and mechanisms that, if provided by a statically typed, object-oriented language, would better support the arXiv:1905.13674v1 [cs.PL] 31 May 2019 implementation of design patterns and, transitively, benefit the construction of many real systems. In particular, our catalog of language constructs includes subtyping separate from inheritance, lexically scoped closure objects independent of classes, and multimethod dispatch. The proposed constructs and mechanisms are not radically new, but rather are adopted from a variety of languages and programming language research and combined in a new, orthogonal manner. We argue that by describing design pat- terns in terms of the proposed constructs and mechanisms, pattern descriptions become simpler and, therefore, accessible to a larger number of language communities.
    [Show full text]
  • An Analysis of the Dynamic Behavior of Javascript Programs
    An Analysis of the Dynamic Behavior of JavaScript Programs Gregor Richards Sylvain Lebresne Brian Burg Jan Vitek S3 Lab, Department of Computer Science, Purdue University, West Lafayette, IN fgkrichar,slebresn,bburg,[email protected] Abstract becoming a general purpose computing platform with office appli- The JavaScript programming language is widely used for web cations, browsers and development environments [15] being devel- programming and, increasingly, for general purpose computing. oped in JavaScript. It has been dubbed the “assembly language” of the Internet and is targeted by code generators from the likes As such, improving the correctness, security and performance of 2;3 JavaScript applications has been the driving force for research in of Java and Scheme [20]. In response to this success, JavaScript type systems, static analysis and compiler techniques for this lan- has started to garner academic attention and respect. Researchers guage. Many of these techniques aim to reign in some of the most have focused on three main problems: security, correctness and dynamic features of the language, yet little seems to be known performance. Security is arguably JavaScript’s most pressing prob- about how programmers actually utilize the language or these fea- lem: a number of attacks have been discovered that exploit the lan- tures. In this paper we perform an empirical study of the dynamic guage’s dynamism (mostly the ability to access and modify shared behavior of a corpus of widely-used JavaScript programs, and an- objects and to inject code via eval). Researchers have proposed ap- alyze how and why the dynamic features are used.
    [Show full text]
  • Thinking in C++ Volume 2 Annotated Solution Guide, Available for a Small Fee From
    1 z 516 Note: This document requires the installation of the fonts Georgia, Verdana and Andale Mono (code font) for proper viewing. These can be found at: http://sourceforge.net/project/showfiles.php?group_id=34153&release_id=105355 Revision 19—(August 23, 2003) Finished Chapter 11, which is now going through review and copyediting. Modified a number of examples throughout the book so that they will compile with Linux g++ (basically fixing case- sensitive naming issues). Revision 18—(August 2, 2003) Chapter 5 is complete. Chapter 11 is updated and is near completion. Updated the front matter and index entries. Home stretch now. Revision 17—(July 8, 2003) Chapters 5 and 11 are 90% done! Revision 16—(June 25, 2003) Chapter 5 text is almost complete, but enough is added to justify a separate posting. The example programs for Chapter 11 are also fairly complete. Added a matrix multiplication example to the valarray material in chapter 7. Chapter 7 has been tech-edited. Many corrections due to comments from users have been integrated into the text (thanks!). Revision 15—(March 1 ,2003) Fixed an omission in C10:CuriousSingleton.cpp. Chapters 9 and 10 have been tech-edited. Revision 14—(January ,2003) Fixed a number of fuzzy explanations in response to reader feedback (thanks!). Chapter 9 has been copy-edited. Revision 13—(December 31, 2002) Updated the exercises for Chapter 7. Finished rewriting Chapter 9. Added a template variation of Singleton to chapter 10. Updated the build directives. Fixed lots of stuff. Chapters 5 and 11 still await rewrite. Revision 12—(December 23, 2002) Added material on Design Patterns as Chapter 10 (Concurrency will move to Chapter 11).
    [Show full text]
  • Ferrite: a Judgmental Embedding of Session Types in Rust
    Ferrite: A Judgmental Embedding of Session Types in Rust RUOFEI CHEN, Independent Researcher, Germany STEPHANIE BALZER, Carnegie Mellon University, USA This paper introduces Ferrite, a shallow embedding of session types in Rust. In contrast to existing session type libraries and embeddings for mainstream languages, Ferrite not only supports linear session types but also shared session types. Shared session types allow sharing (aliasing) of channels while preserving session fidelity (preservation) using type modalities for acquiring and releasing sessions. Ferrite adopts a propositions as types approach and encodes typing derivations as Rust functions, with the proof of successful type-checking manifesting as a Rust program. We provide an evaluation of Ferrite using Servo as a practical example, and demonstrate how safe communication can be achieved in the canvas component using Ferrite. CCS Concepts: • Theory of computation ! Linear logic; Type theory; • Software and its engineering ! Domain specific languages; Concurrent programming languages. Additional Key Words and Phrases: Session Types, Rust, DSL ACM Reference Format: Ruofei Chen and Stephanie Balzer. 2021. Ferrite: A Judgmental Embedding of Session Types in Rust. In Proceedings of International Conference on Functional Programming (ICFP 2021). ACM, New York, NY, USA, 36 pages. 1 INTRODUCTION Message-passing concurrency is a dominant concurrency paradigm, adopted by mainstream lan- guages such as Erlang, Scala, Go, and Rust, putting the slogan “to share memory by communicating rather than communicating by sharing memory”[Gerrand 2010; Klabnik and Nichols 2018] into practice. In this setting, messages are exchanged over channels, which can be shared among several senders and recipients. Figure 1 provides a simplified example in Rust.
    [Show full text]
  • Asynchronous Liquid Separation Types
    Asynchronous Liquid Separation Types Johannes Kloos, Rupak Majumdar, and Viktor Vafeiadis Max Planck Institute for Software Systems, Germany { jkloos, rupak, viktor }@mpi-sws.org Abstract We present a refinement type system for reasoning about asynchronous programs manipulating shared mutable state. Our type system guarantees the absence of races and the preservation of user-specified invariants using a combination of two ideas: refinement types and concurrent separation logic. Our type system allows precise reasoning about programs using two ingredients. First, our types are indexed by sets of resource names and the type system tracks the effect of program execution on individual heap locations and task handles. In particular, it allows making strong updates to the types of heap locations. Second, our types track ownership of shared state across concurrently posted tasks and allow reasoning about ownership transfer between tasks using permissions. We demonstrate through several examples that these two ingredients, on top of the framework of liquid types, are powerful enough to reason about correct behavior of practical, complex, asynchronous systems manipulating shared heap resources. We have implemented type inference for our type system and have used it to prove complex invariants of asynchronous OCaml programs. We also show how the type system detects subtle concurrency bugs in a file system implementation. 1998 ACM Subject Classification F.3.1 Specifying and Verifying and Reasoning about Pro- grams, D.2.4 Software/Program Verification Keywords and phrases Liquid Types, Asynchronous Parallelism, Separation Logic, Type Sys- tems 1 Introduction Asynchronous programming is a common programming idiom used to handle concurrent interactions. It is commonly used not only in low-level systems code, such as operating systems kernels and device drivers, but also in internet services, in programming models for mobile applications, in GUI event loops, and in embedded systems.
    [Show full text]
  • Thinking in C++ 2Nd Edition Volume 2
    Thinking in C++ 2nd edition Volume 2: Standard Libraries & Advanced Topics To be informed of future releases of this document and other information about object- oriented books, documents, seminars and CDs, subscribe to my free newsletter. Just send any email to: [email protected] ________________________________________________________________________ “This book is a tremendous achievement. You owe it to yourself to have a copy on your shelf. The chapter on iostreams is the most comprehensive and understandable treatment of that subject I’ve seen to date.” Al Stevens Contributing Editor, Doctor Dobbs Journal “Eckel’s book is the only one to so clearly explain how to rethink program construction for object orientation. That the book is also an excellent tutorial on the ins and outs of C++ is an added bonus.” Andrew Binstock Editor, Unix Review “Bruce continues to amaze me with his insight into C++, and Thinking in C++ is his best collection of ideas yet. If you want clear answers to difficult questions about C++, buy this outstanding book.” Gary Entsminger Author, The Tao of Objects “Thinking in C++ patiently and methodically explores the issues of when and how to use inlines, references, operator overloading, inheritance and dynamic objects, as well as advanced topics such as the proper use of templates, exceptions and multiple inheritance. The entire effort is woven in a fabric that includes Eckel’s own philosophy of object and program design. A must for every C++ developer’s bookshelf, Thinking in C++ is the one C++ book you must have if you’re doing serious development with C++.” Richard Hale Shaw Contributing Editor, PC Magazine Thinking In C++ 2nd Edition, Volume 2 Bruce Eckel President, MindView Inc.
    [Show full text]
  • C for Java Programmers
    C for Java Programmers George Ferguson Summer 2016 (Updated Summer 2021) 2 Contents 1 Introduction7 2 Overview of Java and C9 2.1 What’s The Same?.........................9 2.2 What’s Different?.......................... 10 3 Development and Execution 11 3.1 Development and Execution in Java and C............. 11 3.2 Setting Up Your Development Environment............ 14 3.3 Writing Your First C Program................... 16 3.4 Compiling Your First C Program.................. 17 4 Basic Expressions and Statements 21 4.1 Comments.............................. 21 4.2 Primitive Types........................... 22 4.3 Producing Output.......................... 23 4.4 Operators and Expressions..................... 24 4.5 Variables and Assigment...................... 26 4.6 Arrays................................ 27 4.7 Strings................................ 29 3 4 CONTENTS 5 Control Flow 31 5.1 Conditional Statements....................... 31 5.2 Iteration Statements......................... 32 5.3 Other Control Flow Statements................... 33 6 Functions 35 6.1 Function Parameters and Arguments................ 36 6.2 Function Declarations........................ 37 7 Structured Types 39 8 Memory Management 43 8.1 Variables, Addresses, and Pointers................. 43 8.2 Passing Arguments by Reference.................. 46 8.3 Memory Allocation......................... 48 8.4 Dynamic Memory Allocation in Java................ 49 8.5 Dynamic Memory Allocation in C................. 50 8.6 Dynamic Arrays........................... 54 8.7 Dynamic Data Structures...................... 56 8.8 Function Pointers.......................... 64 9 Defining New Types 69 10 Sharing Code: Files and Libraries 73 10.1 The C Preprocessor......................... 73 10.2 Separate Compilation, Libraries, and Linking........... 75 10.3 Standard System Libraries..................... 76 CONTENTS 5 10.4 Project Development........................ 77 10.5 Building Larger C Programs.................... 79 11 Debugging a C Program 83 11.1 Debuggers.............................
    [Show full text]
  • Refining Expression Evaluation Order for Idiomatic C++ (Revision 2)
    P0145R1 2016-02-12 Reply-To: [email protected] Refining Expression Evaluation Order for Idiomatic C++ (Revision 2) Gabriel Dos Reis Herb Sutter Jonathan Caves Abstract This paper proposes an order of evaluation of operands in expressions, directly supporting decades-old established and recommended C++ idioms. The result is the removal of embarrassing traps for novices and experts alike, increased confidence and safety of popular programming practices and facilities, hallmarks of modern C++. 1. INTRODUCTION Order of expression evaluation is a recurring discussion topic in the C++ community. In a nutshell, given an expression such as f(a, b, c), the order in which the sub-expressions f, a, b, c (which are of arbitrary shapes) are evaluated is left unspecified by the standard. If any two of these sub-expressions happen to modify the same object without intervening sequence points, the behavior of the program is undefined. For instance, the expression f(i++, i) where i is an integer variable leads to undefined behavior, as does v[i] = i++. Even when the behavior is not undefined, the result of evaluating an expression can still be anybody’s guess. Consider the following program fragment: #include <map> int main() { std::map<int, int> m; m[0] = m.size(); // #1 } What should the map object m look like after evaluation of the statement marked #1? {{0, 0}} or {{0, 1}}? 1.1. CHANGES FROM PREVIOUS VERSIONS a. The original version of this proposal (Dos Reis, et al., 2014) received unanimous support from the Evolution Working Group (EWG) at the Fall 2014 meeting in Urbana, IL, as approved direction, and also strong support for inclusion in C++17.
    [Show full text]
  • Long X T 2021.Pdf (989.3Kb)
    Understanding Common Scratch Programming Idioms and Their Impact on Project Remixing Xingyu Long Thesis submitted to the Faculty of the Virginia Polytechnic Institute and State University in partial fulfillment of the requirements for the degree of Master of Science in Computer Science and Applications Eli Tilevich, Chair Osman Balci Dimitrios S. Nikolopoulos May 10, 2021 Blacksburg, Virginia Keywords: Programming idioms; Scratch; Block-based programming; Novice programmers; Project remixing; Copyright 2021, Xingyu Long Understanding Common Scratch Programming Idioms and Their Im- pact on Project Remixing Xingyu Long (ABSTRACT) As Scratch has become one of the most popular educational programming languages, under- standing its common programming idioms can benefit both computing educators and learn- ers. This understanding can fine-tune the curricular development to help learners master the fundamentals of writing idiomatic code in their programming pursuits. Unfortunately, the research community’s understanding of what constitutes idiomatic Scratch code has been limited. To help bridge this knowledge gap, we systematically identified idioms as based on canonical source code, presented in widely available educational materials. We implemented a tool that automatically detects these idioms to assess their prevalence within a large dataset of over 70K Scratch projects in different demographic and project categories. Since communal learning and the practice of remixing are one of the cornerstones of the Scratch programming community, we studied the relationship between common programming idioms and remixes. Having analyzed the original projects and their remixes, we observed that different idioms may associate with dissimilar types of code changes. Code changes in remixes are desirable, as they require a meaningful programming effort that spurs the learning process.
    [Show full text]
  • Types You Can Count on Like Types for Javascript
    Types you can count on Like types for JavaScript Abstract As the need for error reporting was felt in industry, develop- Scripting languages support exploratory development by eschew- ers adopted a “dynamic first” philosophy, which led to the design ing static type annotations but fall short when small scripts turn into of optional type systems for languages such as Smalltalk, PHP and large programs. Academic researchers have proposed type systems JavaScript [3, 4, 11, 16, 20]. Optional type systems have two rather that integrate dynamic and static types, providing robust error re- surprising properties: they do not affect the program’s execution ports when the contract at the boundary between the two worlds is and they are unsound. These are design choices motivated by the violated. Safety comes at the price of pervasive runtime checks. On need to be backwards compatible and to capture popular program- the other hand, practitioners working on massive code bases have ming idioms used in scripting languages. Rather than limiting ex- come up with type systems that are unsound and that are ignored pressiveness of the language to what can shown to be type safe, at runtime, but which have proven useful in practice. This paper this design instead limits the type system. For example, Hack [20], proposes a new design for the JavaScript language, combining dy- Facebook’s optionally typed PHP dialect, has an UNSAFE direc- namic types, concrete types and like types to let developers pick tive that turns off type checking for the remainder of a block. Un- the level of guarantee that is appropriate for their code.
    [Show full text]