http://wiki.mohid.com/api.php?action=feedcontributions&user=89.180.146.64&feedformat=atom
MohidWiki - User contributions [en]
2024-03-28T08:35:46Z
User contributions
MediaWiki 1.28.0
http://wiki.mohid.com/index.php?title=Cpp&diff=162
Cpp
2008-03-15T01:23:06Z
<p>89.180.146.64: /* IO string manipulations */</p>
<hr />
<div>This page is kind of a handbook for writing c and c++ programs. References to practical issues are assigned to this page.<br />
<br />
== GOLDEN RULES ==<br />
<br />
# '''In a function, never pass the arguments by value, always pass them by reference'''<br />
<br />
== Single file [http://en.wikipedia.org/wiki/ANSI_C ANSI C] project template ==<br />
<br />
Here's a basic template for a single-file project:<br />
<code>[c,Y]<br />
/*Template for a [http://en.wikipedia.org/wiki/ANSI_C ANSI C] standard program file*/<br />
<br />
/*Place the headers here*/<br />
#include <stdio.h><br />
#include <math.h><br />
<br />
/*Place the Macros here*/<br />
#define OK_ 1<br />
<br />
/*Place the Casts here*/<br />
typedef double REAL_T; <br />
<br />
/*Place the subroutines declaration here*/<br />
REAL_T deg(REAL_T x);<br />
<br />
/*Main routine*/<br />
int main(int argc, char* argv[])<br />
{<br />
/*...*/<br />
return 1;<br />
}<br />
/*Subroutines*/<br />
REAL_T deg(REAL_T x){<br />
return x/fabs(x)*floor(fabs(x));<br />
}<br />
</code><br />
<br />
== Mixing C and C++ code ==<br />
<br />
In order to mix C routines within a C++ structure simply make sure that the C routines are written in standard [http://en.wikipedia.org/wiki/ANSI_C ANSI C] and that they're all in a separate file. Then include ''extern "C"'' syntax. Here's an example:<br />
<br />
<code>[cpp,Y]<br />
#include <sstream><br />
#include <string><br />
#include <math.h><br />
extern "C"{<br />
#include <fes.h><br />
}<br />
</code><br />
<br />
== Using namespaces ==<br />
<br />
Whenever one whishes to use C++ STL standard libraries then one has to use the '''std::''' namespace. Or it can be declared in the beginning of the routine or of the code:<br />
<br />
<code>[cpp,Y] <br />
#include <vector><br />
#include <string><br />
#include <sstream><br />
<br />
int main()<br />
{<br />
std::string str;<br />
</code><br />
or<br />
<code>[cpp,Y] <br />
#include <vector><br />
#include <string><br />
#include <sstream><br />
<br />
using namespace std;<br />
<br />
int main()<br />
{<br />
string str;<br />
</code><br />
<br />
== Variables in C and C++ ==<br />
<br />
There are several built-in types of variables:<br />
<code>[c,Y] <br />
char c; //byte size character [0x0-FFx0]<br />
short int sn; //byte sized integer [0-255]<br />
int n; //word(2bytes) sized integer [0-16556]<br />
long ln; // 4 byte sized integer<br />
float x; // single precision real number<br />
double dx; // double precision real number<br />
</code><br />
=== Memory structure and pointers ===<br />
In C coding, a variable is in fact the combination of two elements: its value and its pointer:<br />
*The value is a memory register where the variable value is stored.<br />
*The pointer is another memory register containing the memory address of the variable value. <br />
Thus the pointer points to the variable value.<br />
<code>[c,Y] <br />
char* c_p; //pointer to characters<br />
short int* sn_p; //pointer to short integers<br />
int* n_p; //pointer to integers<br />
long* ln_p; // pointer to long integers<br />
float* x_p; // pointer to single precision real numbers<br />
double* dx_p; // pointer to double precision real numbers<br />
</code><br />
==== Allocate arrays ====<br />
<br />
In C, pointers allow to allocate arrays (blocks of memory) of a given variable single type...<br />
Here's an example of allocating a memory block:<br />
<code>[c,Y] <br />
double* vector_p; //Allocates the memory register of the pointer, and fills it with dumb address<br />
vector_p = (double*) malloc( sizeof(double)*(N + 2*p) ) // Allocates a block of memory and assigns<br />
//its memory address to vector_p.<br />
</code><br />
<br />
=== [http://en.wikipedia.org/wiki/Cast_%28computer_science%29 Cast] of types of variables ===<br />
<br />
[http://en.wikipedia.org/wiki/Cast_%28computer_science%29 Casts] are a very useful feature of [http://en.wikipedia.org/wiki/C_programming_language C programming language]. They allow to define custom types of variables. They are defined at the beginning of the code. When well used, [http://en.wikipedia.org/wiki/Cast_%28computer_science%29 casts] allow easy portability from single to double precision computing. Here are a few examples:<br />
<br />
<code>[c,Y] <br />
typedef float REAL_SCALAR_T;<br />
/*typedef double REAL_SCALAR_T;*/<br />
typedef REAL_SCALAR_T* REAL_VECTOR_T;<br />
<br />
REAL_SCALAR_T x = 3.1416;<br />
REAL_VECTOR_T vx;<br />
</code><br />
<br />
The above code defines single precision scalar and vector variables types.<br />
<br />
<code>[c,Y] <br />
typedef int INT_SCALAR_T;<br />
/*typedef long INT_SCALAR_T;*/<br />
typedef INT_SCALAR_T* INT_VECTOR_T;<br />
<br />
INT_SCALAR_T n = 7;<br />
INT_VECTOR_T v;<br />
</code><br />
<br />
The above code defines single precision integer and integer vector variables types.<br />
<br />
=== Structures ===<br />
Structures are composites of several types of variables. A typical syntax example would be:<br />
<br />
<code>[c,Y] <br />
struct s_myexample{<br />
char a;<br />
int b; <br />
float* ptr_p;<br />
}<br />
<br />
char ext = s_myexample.a;<br />
</code><br />
<br />
Combining structures with casts is much more useful:<br />
<code>[c,Y] <br />
typedef struct s_myexample{<br />
char a;<br />
int b;<br />
s_myexample_t* myotherexample_p;<br />
}s_myexample_t;<br />
</code><br />
<br />
== [http://en.wikipedia.org/wiki/Macro Macros] ==<br />
<br />
The C or C++ compiler comes with [http://en.wikipedia.org/wiki/Preprocessor preprocessing] capabilities. Hence [http://en.wikipedia.org/wiki/Macro macros] are allowed, but use them with care. Here are a few examples for syntax purposes. Preferrably, define at head of the code.<br />
<code>[c,Y] <br />
#define OK_ 1<br />
#define BAD_ -1<br />
#define DATA_ 1<br />
#define INPUT_ 2<br />
</code><br />
<br />
== IO string manipulations ==<br />
<br />
To perform simple output to the console:<br />
<code>[cpp,Y] <br />
std::cout << "ERROR: Too many parameters included in command line!\n" << std::endl;<br />
</code><br />
<br />
== Building the project ==<br />
<br />
=== Building a single file project ===<br />
g++ -c -o example.o -Iincludepath example.cpp<br />
g++ -o example.exe -Llibpath example.o alibrary.a<br />
The first line compiles example.cpp and outputs the object example.o. The second line links the object file agains a library (static or shared).<br />
<br />
=== Building a several files project ===<br />
CC="g++"<br />
INC="-Iincludepath1 -Iincludepath2 -Iincludepath3"<br />
LIB="-Llibpath1 -Llibpath2"<br />
SRC="file1.cpp file2.cpp file3.cpp"<br />
OBJ="file1.o file2.o file3.o lib1.a lib2.a"<br />
<br />
$CC -c $INC $SRC<br />
$CC -o example.exe $LIB $OBJ<br />
The first line compiles and returns the object files. The second line links against the libraries (static or shared).<br />
<br />
=== Creating a makefile for the project ===<br />
<br />
Usually, the [http://en.wikipedia.org/wiki/Integrated_Development_Environment IDE] takes care of the [http://en.wikipedia.org/wiki/Make making] of the project. However when porting to other environments such as [[*NIX platforms]] then one may want to consider to create a [[makefile]].<br />
[[Category:Technology]]<br />
[[Category:Programming]]<br />
[[Category:Linux]]<br />
[[Category:Windows]]</div>
89.180.146.64
http://wiki.mohid.com/index.php?title=Makefile&diff=456
Makefile
2008-03-15T01:17:07Z
<p>89.180.146.64: /* Mohid_Base_1 */</p>
<hr />
<div>A makefile is a script run by make (or nmake under windows) that contains information about the dependencies of a series of targets and, additionally, makes them. For example, make can build the binaries for a large software project.<br />
<br />
== Syntax ==<br />
Here's the syntax to use the make command:<br />
make ''Target''<br />
make -C ''Subdir'' ''Target''<br />
make -f ''filename'' ''Target''<br />
''(ex: make -f mymakefile all).''<br />
<br />
In most projects in linux, the most common targets are:<br />
*''all'': builds the full project.<br />
*''install'': copies the executable files in their final destination on the system.<br />
*''clean'': deletes the object and the executable files created by target ''all''.<br />
<br />
''NOTE: Here's how to ignore built-in pattern rules!!''<br />
> make -r target<br />
This is very important for the following rules:<br />
%.o : %.c<br />
%.dvi : %.aux<br />
<br />
== [[Makefile methodologyP|A large project cross-platform, cross-compiler makefile methodology]] ==<br />
[[Makefile CCCP|Here]] is described a CCCP makefile methodology particularly suitable for [[MOHID]].<br />
<br />
== Sample makefiles ==<br />
In particular, the gnumake program is very documented [http://www.gnu.org/software/make/manual/make.html here].<br />
=== [[Mohid_Base_1]] ===<br />
The source code of a sample [[Makefile]] is given bellow:<br />
<code>[makefile,Y]<br />
#<br />
# Use GNUmake! <br />
# Win32: rename gmake.exe to make.exe and load ifortvars.bat<br />
# *nix: load ifortvars.sh<br />
#<br />
<br />
SHELL = /bin/sh <br />
<br />
.SUFFIXES:<br />
.SUFFIXES: .f90 .o<br />
<br />
DEL = rm -f<br />
<br />
BIN = ./bin<br />
MOD = ./mod<br />
SRC = .<br />
OBJ = .<br />
<br />
#-----Users: edit these lines!!!----------<br />
#*nix vs windows<br />
#Uncomment one of these<br />
#HDF5 = ../IntelLibs<br />
#MODOPT = -module:$(MOD)<br />
#OBJOPT = -object:$*.o<br />
HDF5 = /opt/hdf5/hdf5/lib<br />
MODOPT = -module $(MOD)<br />
OBJOPT = -o $*.o<br />
#-----Users: end of block ----------------<br />
<br />
TARGET = $(BIN)/mohidbase1.lib<br />
<br />
CC = ifort<br />
CCFLAGS = -c -fpp -nologo<br />
AR = ar rc<br />
#--------Users: fill these lines with your sourcesafe data-------------<br />
SERVER = <br />
USER = <br />
PASS = <br />
SOSHOME = <br />
PROJECT = Mohid_Base_1<br />
GET = soscmd -command GetFile \<br />
-server $(SERVER):8890 \<br />
-name $(USER) -password $(PASS) \<br />
-database "W:\SourceSafe\Mohid_v4\srcsafe.ini" \<br />
-project $(PROJECT) \<br />
-soshome $(SOSHOME) \<br />
-file <br />
#--------End of sourcesafe data-------------<br />
<br />
#Rules to apply to a standard .o file<br />
.f90.o:<br />
@$(CC) $(CCFLAGS) $< $(OBJOPT) $(MODOPT)<br />
@echo $* ......... [OK]<br />
<br />
OBJS = \<br />
ModuleGlobalData.o \<br />
ModuleTime.o \<br />
ModuleEnterData.o \<br />
ModuleFunctions.o \<br />
ModuleBenthos.o \<br />
ModuleCEQUALW2.o \<br />
ModuleTimeSerie.o \<br />
ModuleDischarges.o \<br />
ModuleDrawing.o \<br />
ModuleLUD.o \<br />
ModuleWaterQuality.o \<br />
ModuleSedimentQuality.o \<br />
ModuleLife.o \<br />
ModuleInterface.o \<br />
ModuleHydroIntegration.o \<br />
ModuleLightExtinction.o \<br />
ModuleStopWatch.o \<br />
ModuleTriangulation.o \<br />
ModuleHDF5.o \<br />
ModuleDrainageNetwork.o \<br />
ModuleProfile.o<br />
<br />
.PHONY: all clean<br />
<br />
all: $(TARGET)<br />
@echo<br />
@echo Finished building $(TARGET)<br />
@echo<br />
<br />
$(TARGET) : $(OBJS)<br />
@$(AR) $(TARGET) $(OBJS)<br />
@echo $(TARGET) ....... [OK]<br />
<br />
clean : <br />
@-$(DEL) *.o $(MOD)/*.mod $(BIN)/*.lib<br />
@echo $(TARGET) ......... [Erased]<br />
<br />
#This command here gets out of sourcesafe the latest version<br />
sos: $(OBJS:.o=)<br />
<br />
$(OBJS:.o=)::<br />
@-$(GET) $@.f90<br />
@echo $@.f90 ....... [Updated]<br />
<br />
#--------Dependencies list-------------<br />
<br />
ModuleGlobalData.o : ModuleGlobalData.f90<br />
<br />
ModuleTime.o : ModuleGlobalData.o \<br />
ModuleTime.f90<br />
<br />
ModuleEnterData.o : ModuleTime.o \<br />
ModuleEnterData.f90<br />
<br />
ModuleFunctions.o : ModuleEnterData.o \<br />
ModuleFunctions.f90<br />
<br />
ModuleBenthos.o : ModuleEnterData.o \<br />
ModuleBenthos.f90<br />
<br />
ModuleCEQUALW2.o : ModuleFunctions.o \<br />
ModuleCEQUALW2.f90<br />
<br />
ModuleTimeSerie.o : ModuleEnterData.o \<br />
ModuleTimeSerie.f90<br />
<br />
ModuleDischarges.o : ModuleFunctions.o \<br />
ModuleTimeSerie.o \<br />
ModuleDischarges.f90<br />
<br />
ModuleDrawing.o : ModuleFunctions.o \<br />
ModuleDrawing.f90<br />
<br />
ModuleLUD.o : ModuleGlobalData.o \<br />
ModuleLUD.f90<br />
<br />
ModuleWaterQuality.o : ModuleFunctions.o \<br />
ModuleLUD.o \<br />
ModuleWaterQuality.f90<br />
<br />
ModuleSedimentQuality.o : ModuleFunctions.o \<br />
ModuleLUD.o \<br />
ModuleSedimentQuality.f90<br />
<br />
ModuleLife.o : ModuleFunctions.o \<br />
ModuleLife.f90<br />
<br />
ModuleInterface.o : ModuleWaterQuality.o \<br />
ModuleSedimentQuality.o \<br />
ModuleCEQUALW2.o \<br />
ModuleLife.o \<br />
ModuleBenthos.o \<br />
ModuleInterface.f90<br />
<br />
ModuleHydroIntegration.o : ModuleTime.o \<br />
ModuleHydroIntegration.f90<br />
<br />
ModuleLightExtinction.o : ModuleFunctions.o \<br />
ModuleTimeSerie.o \<br />
ModuleLightExtinction.f90<br />
<br />
ModuleStopWatch.o : ModuleTime.o \<br />
ModuleStopWatch.f90<br />
<br />
ModuleTriangulation.o : ModuleGlobalData.o \<br />
ModuleTriangulation.f90<br />
<br />
#The following module requires the HDF5 mod files<br />
ModuleHDF5.o : ModuleGlobalData.o \<br />
ModuleHDF5.f90<br />
@$(CC) $(CCFLAGS) -I$(HDF5) $*.f90 $(OBJOPT) $(MODOPT)<br />
@echo $* ......... [OK]<br />
<br />
ModuleDrainageNetwork.o : ModuleDischarges.o \<br />
ModuleLightExtinction.o \<br />
ModuleStopWatch.o \<br />
ModuleInterface.o \<br />
ModuleDrainageNetwork.f90<br />
<br />
ModuleProfile.o : ModuleEnterData.o \<br />
ModuleHDF5.o \<br />
ModuleProfile.f90<br />
<br />
#--------End of dependencies list---------<br />
</code><br />
<br />
===ADCP to AVU===<br />
SHELL = /bin/sh <br />
<br />
#CCCPEV (Cross-Compiler, Cross-Platform Environment Variables)<br />
CC=gcc<br />
CCFLAGS=-c<br />
LCFLAGS= <br />
OCFLAG=-o <br />
RM=del<br />
H=h<br />
C=c<br />
O=o<br />
A=exe<br />
D=tds<br />
L=lib<br />
<br />
#Files list<br />
TARGET=adcp_avu.$(A)<br />
SRC=adcp_avu_this.$(C) readstring.$(C)<br />
OBJ=$(SRC:.$(C)=.$(O))<br />
LIB=<br />
HDR=$(SRC:.$(C)=.$(H))<br />
<br />
#Action "make all"<br />
.PHONY=all<br />
all : $(TARGET)<br />
-$(RM) $(OBJ) $(^:.$(A)=.$(D)) <br />
<br />
$(TARGET) : $(LIB) $(OBJ)<br />
$(CC) $(LCFLAGS) $(OCFLAG)$@ $^<br />
<br />
$(LIB) : <br />
@echo Warning: $@ is missing.<br />
<br />
%.$(O) : %.$(C)<br />
$(CC) $(CCFLAGS) $<<br />
<br />
#Action "make clean"<br />
.PHONY=clean<br />
clean :<br />
-$(RM) $(OBJ) $(TARGET) $(TARGET:.$(A)=.$(D))<br />
<br />
#Dependencies list<br />
%.$(C) : %.$(H) #Fortran is %.$(H) : %.$(O)<br />
adcp_avu_this.$(O) : readstring.$(H)<br />
<br />
===Mururoa===<br />
Here's another sample [http://en.wikipedia.org/wiki/Make makefile] made for \\guillaume\projects\mururoa<br />
based on [[*NIX_platforms]] and on [http://www.eng.hawaii.edu/Tutor/Make/index.html this] tutorial.<br />
<br />
SHELL = /bin/sh <br />
<br />
#Suffixes which we'll be working on<br />
.SUFFIXES: .cpp .o<br />
<br />
#windows/linux bash commands<br />
COPY = xcopy /-Y<br />
DEL = del /Q <br />
<br />
BIN = ../bin<br />
INC = ../inc<br />
SRC = .<br />
OBJ = .<br />
LIB = ../lib <br />
<br />
CC = gcc<br />
CCFLAGS = -c -I$(INC)<br />
LFLAGS = -L$(LIB)<br />
CPP = g++<br />
<br />
#Rules to apply to a standard .o file<br />
.cpp.o:<br />
$(CC) $(CCFLAGS) ./$<<br />
<br />
OBJS = \<br />
prog_3d.o \<br />
prog_prm.o \<br />
prog_io.o \<br />
prog_cdf_out.o \<br />
prog_cdf.o \<br />
prog_blc.o \<br />
prog_all.o \<br />
msnemo.o <br />
<br />
INCS = \<br />
$(INC)/StdAfx.h \<br />
$(INC)/prog_3d.h \<br />
$(INC)/prog_all.h \<br />
$(INC)/prog_blc.h \<br />
$(INC)/prog_boo.h \<br />
$(INC)/prog_cdf.h \<br />
$(INC)/prog_cdf_out.h \<br />
$(INC)/prog_ind.h \<br />
$(INC)/prog_io.h \<br />
$(INC)/prog_prm.h \<br />
$(INC)/prog_mai.h \<br />
$(INC)/prog_switches.h \ <br />
<br />
LIBS = \<br />
$(LIB)/netcdf.lib<br />
<br />
#Compiles the full solution and cleans the intermediate files<br />
all: msnemo postclean <br />
<br />
#Makes the main executable<br />
#links the object files against the libraries<br />
msnemo: $(OBJS)<br />
$(CPP) $(LFLAGS) -o $(BIN)/$@.exe $(OBJS) $(LIBS)<br />
<br />
#Cleans to the original distro<br />
clean:<br />
-$(DEL) *.o<br />
<br />
#Cleans everything except binaries, source and object files<br />
postclean:<br />
<br />
#Installs the binaries in the right places of the system<br />
install:<br />
<br />
#Dependencies<br />
prog_3d.o: $(INCS)<br />
prog_prm.o: $(INCS)<br />
prog_io.o: $(INCS)<br />
prog_cdf_out.o: $(INCS)<br />
prog_cdf.o: $(INCS)<br />
prog_blc.o: $(INCS)<br />
prog_all.o: $(INCS)<br />
msnemo.o: $(INCS)<br />
<br />
==Troubleshoots==<br />
===use DFWIN===<br />
This is a windows platform specific library. It cannot be ported to Linux. To build the code in linux you need to change it first. This is currently(20061201) the case in ''ModuleGlueHDF5''. If you get an error attempting to make it in windows, first make sure you're calling [[makefile|make]] inside an Intel Fortran Development Console, which is where all the environment variables are correct.<br />
==='''ifconsol'''===<br />
If you get an error about an "ifconsol", then it's probably because you have incorrect environment variables. Under windows, make sure you're inside an Intel Fortran Development Console.<br />
<br />
== Other references ==<br />
# The Wikipedia [http://en.wikipedia.org/wiki/Make article].<br />
# The [http://www.gnu.org/software/make/manual/make.html GNUMake] documentation. A classic standard.<br />
# [http://www.eng.hawaii.edu/Tutor/Make/index.html Here's] a popular tutorial.<br />
# The 20060629 workshop [http://www.mohid.com/hydrogroup/presentations/HG_060629_Formacao_Makefiles.ppt powerpoint].<br />
[[Category:Technology]]<br />
[[Category:Linux]]<br />
[[Category:Windows]]<br />
[[Category:Makefile]]</div>
89.180.146.64
http://wiki.mohid.com/index.php?title=Perl&diff=755
Perl
2008-03-15T01:15:48Z
<p>89.180.146.64: /* ConvertToHDF5 */</p>
<hr />
<div>Perl is a powerful and versatile scripting language that comes in handy when bot-working is needed on any operating system.<br />
<br />
==Installing==<br />
To use the perl scripting language, first you need to install it on your operating system.<br />
*To install packages type:<br />
>perl -MCPAN -e shell<br />
CPAN> install ''packagename''<br />
CPAN> force install ''packagename''<br />
(ex: install Date::Calc). '''Warning''': under windows use a .NET environment command prompt!!<br />
*To run a perl script type:<br />
>perl ''scriptfile''<br />
(ex: perl test.pl).<br />
<br />
===Installing for windows===<br />
If you are one of the unlucky Visual Studio 2005 owners, then you'd better install the [http://sourceforge.net/project/showfiles.php?group_id=158775&package_id=178025 CamelPack] or else you won't be able to install perl modules from CPAN. Microsoft did there a hard blow against the Perl community.<br />
<br />
===Common extensions===<br />
Here are the common extensions used:<br />
<br />
use Net::FTP;<br />
use Net::SMTP;<br />
use IO::File;<br />
use Date::Calc;<br />
use NetCDF;<br />
<br />
===PPM===<br />
The Perl Package Manager is here to help installing and managing Perl packages. The greatest asset of Perls longevity is its package repository with over 6500 packages!<br />
Here are some of the commands that best explain how to use ppm:<br />
<br />
> ppm list<br />
will list installed packages.<br />
<br />
> ppm help<br />
> ppm help ''command''<br />
will return help manual.<br />
<br />
> ppm search ''pattern''<br />
> ppm search *<br />
will return a numbered list of downloadable packages matching ''pattern''.<br />
<br />
> ppm describe ''pkg''<br />
> ppm describe ''module''<br />
> ppm describe ''url''<br />
> ppm describe ''number''<br />
will describe the selected package. Note that ''number'' is the package number taken from the last search.<br />
<br />
> ppm install ''pkg''<br />
> ppm install ''module''<br />
> ppm install ''url''<br />
> ppm install ''number''<br />
will install the desired package. Note that ''number'' is the package number taken from the last search.<br />
==Variables, arrays and hashes==<br />
===Variables===<br />
===Arrays===<br />
===Hashes===<br />
Here's a sample hash construction<br />
%hash = (<br />
key1 => 'value1',<br />
key2 => 'value2',<br />
key3 => 'value3',<br />
);<br />
Here's a simple hash entry definition<br />
$hash{$key} = $value;<br />
<br />
==Flow control==<br />
===For===<br />
===While===<br />
while ( ($key, $value) = each(%$nc_ref) ) {<br />
print "$key => $value \n";<br />
}<br />
<br />
===Foreach===<br />
foreach $thing (@list){<br />
$machine = $thing;<br />
$filesize = $thingy;<br />
$filename = $thingabob;<br />
write;<br />
}<br />
<br />
==[[Regexp]]==<br />
<br />
===matching===<br />
Returns true if ''pattern'' is found in ''$sample''<br />
$sample =~ m/pattern/<br />
<br />
===Substituting===<br />
Substitutes the ''pattern'' with ''newtext'' in every occurence of string ''sample'' and writes the changes into ''sample''.<br />
$sample =~ s/pattern/newtext/g<br />
<br />
===Translate===<br />
Translates an ascii letter for another. It applies to patterns as well.<br />
$sample =~ tr/,\./; /g<br />
The above examples changes the commas(,) for semi-colons(;) and points(.) for spaces( ).<br />
<br />
==[[Perl one-liners|One-Liners]]==<br />
Perl is mighty powerful from the shell command line, simply by invoking [[Perl one-liners|one-liners]] and [[pipes]].<br />
<br />
==Formatting text output==<br />
This snippet typifies how to format text in perl.<br />
*'''>''' justifies right<br />
*'''<''' justifies left<br />
*'''|''' justifies center<br />
format =<br />
@>>>>>>>>>>>>>> @>>>>>>>>>> @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><br />
$machine, $filesize, $filename<br />
.<br />
<br />
foreach $thing (@list){<br />
$machine = $$thing[0];<br />
$filesize = $$thing[1];<br />
$filename = $$thing[2];<br />
write;<br />
}<br />
<br />
==Sample files==<br />
=== Example of a script skeleton ===<br />
<code>[perl,Y]<br />
#!/usr/bin/perl -w<br />
use strict;<br />
<br />
##<br />
## Usage Information<br />
##<br />
<br />
my $usage = <<EOF;<br />
<br />
$0 <argument1> <argument2> <br />
This script does this and needs <arguments><br />
<br />
EOF<br />
<br />
##<br />
## Parse Arguments<br />
##<br />
<br />
if ($#ARGV < 1) {<br />
print $usage;<br />
exit 1;<br />
};<br />
<br />
my $arg1 = shfit(@ARGV);<br />
my $arg2 = shfit(@ARGV);<br />
<br />
##<br />
## Begin<br />
##<br />
<br />
$stat = system("ls *");<br />
&DieNice ($stat, "ERROR on ls *");<br />
<br />
##<br />
## Subroutines<br />
##<br />
<br />
sub DieNice {<br />
<br />
my ($stat, $msg) = @_;<br />
die "$msg \n" if ($stat !=0);<br />
<br />
};<br />
</code><br />
<br />
===Manipulate [[netcdf]] files===<br />
<code>[perl,Y]<br />
#!/usr/bin/perl -w<br />
#<br />
#netcdf rivers {<br />
#dimensions:<br />
# river = 3 ;<br />
# time = UNLIMITED ; // (366 currently)<br />
#variables:<br />
# int river(river) ;<br />
# river:title = "Number of river" ;<br />
# river:long_name = "1:Loire 2:Gironde 3:Adour" ;<br />
# float time(time) ;<br />
# time:units = "seconds since 2004-01-01 00:00:00" ;<br />
# time:title = "Time" ;<br />
# float runoff(time, river) ;<br />
# runoff:long_name = "Runoff of the river" ;<br />
# runoff:units = "m3s-1" ;<br />
# float temperature(time, river) ;<br />
# temperature:long_name = "Temperature" ;<br />
# temperature:units = ".C" ;<br />
# float salinity(time, river) ;<br />
# salinity:long_name = "Salinity" ;<br />
# salinity:units = "PSU" ;<br />
#<br />
#// global attributes:<br />
# :title = "Runoff data" ;<br />
# :institution = "GIP MERCATOR OCEAN" ;<br />
# :references = "http://www.mercator-ocean.fr" ;<br />
#}<br />
#---------------------------------<br />
<br />
use NetCDF;<br />
use strict;<br />
<br />
# Input netcdf filename<br />
my $infile = "rivers.nc";<br />
<br />
#Two dimensions: time(366) and rivers(3). Stride one river at a time.<br />
my %riv = (<br />
Loire => 0,<br />
Gironde => 1,<br />
Adour => 2,<br />
);<br />
<br />
# Choose between Loire, Gironde or Adour<br />
my $key = 'Gironde';<br />
print "Doing river $key\n\n";<br />
<br />
my $len=366;<br />
my @start = (0, 0);<br />
my @count = ($len, 3);<br />
my @slice =();<br />
for (my $i=0; $i<$len; $i++) {<br />
push (@slice, $i*3 + $riv{$key});<br />
}<br />
print "@slice\n";<br />
<br />
# Open netcdf file in read-only mode<br />
my $ncid = NetCDF::open($infile, NetCDF::NOWRITE);<br />
print "ncid: $ncid\n";<br />
<br />
# Dimensions<br />
my $d_rivid = NetCDF::dimid($ncid, 'river');<br />
print "d_rivid: $d_rivid\n";<br />
<br />
my $d_timeid = NetCDF::dimid($ncid, 'time');<br />
print "d_timeid: $d_timeid\n";<br />
<br />
# Variables<br />
my @river = ();<br />
my $rivid = readvar($ncid, 'river', (0), (3), \@river);<br />
print "@river\n\n";<br />
<br />
my @time = ();<br />
my $timeid = readvar($ncid, 'time', (0), (366), \@time);<br />
#print "@time\n\n";<br />
<br />
my @runoff = ();<br />
my $runoffid = readvar($ncid, 'runoff', \@start, \@count, \@runoff);<br />
my @runoff_s = @runoff[@slice];<br />
print "@runoff_s\n\n";<br />
<br />
my @temperature = ();<br />
my $temperatureid = readvar($ncid, 'temperature', \@start, \@count, \@temperature);<br />
my @temperature_s = @temperature[@slice];<br />
print "@temperature_s\n\n";<br />
<br />
my @salinity = ();<br />
my $salinityid = readvar($ncid, 'salinity', \@start, \@count, \@salinity);<br />
my @salinity_s = @salinity[@slice];<br />
print "@salinity_s\n\n";<br />
<br />
# Creating time in days variables<br />
my @timeday = ();<br />
for (my $i=0; $i<$len; $i++) {<br />
push (@timeday,$time[$i]/86400);<br />
}<br />
print "@timeday\n\n";<br />
<br />
# Close netcdf file<br />
NetCDF::close($ncid);<br />
<br />
# Write the TimeSeries dat file<br />
writetimeserie (<br />
<br />
$key, <br />
\@timeday, <br />
\@runoff_s, <br />
\@temperature_s, <br />
\@salinity_s,<br />
<br />
);<br />
<br />
sub readvar {<br />
# syntax: <br />
# my var = "";<br />
# my varid = readvar($ncid, $varname, \@start, \@count, \@var);<br />
<br />
my $ncid = shift;<br />
my $varname = shift;<br />
my $start = shift;<br />
my $count = shift;<br />
my $var_ref = shift;<br />
<br />
my $varid = NetCDF::varid($ncid, $varname);<br />
print "${varname}id: $varid\n";<br />
my @tempvar = (0,0);<br />
my $status = NetCDF::varget($ncid, $varid, $start, $count, \@tempvar);<br />
print "Status: $status\n";<br />
#print "@tempvar\n";<br />
#Copy array<br />
@$var_ref = @tempvar;<br />
<br />
return $varid;<br />
<br />
}<br />
<br />
sub writetimeserie {<br />
# Syntax:<br />
# writetimeserie($rivername, \@timedays, \@runoff, \@temperature, \@salinity);<br />
<br />
my $rivername = shift;<br />
my $timev = shift;<br />
my $runv = shift;<br />
my $tempv = shift;<br />
my $saltv = shift;<br />
<br />
print "$#$timev\n";<br />
<br />
#Open file to write<br />
$rivername.=".srw";<br />
open(FILE, ">$rivername");<br />
<br />
print FILE "TIME_UNITS : DAYS\n"; <br />
print FILE "SERIE_INITIAL_DATA : 2004 1 1 0 0 0\n\n";<br />
<br />
my $time = 'Tempo';<br />
my $flow = ' Flow';<br />
my $temp = ' T';<br />
my $salt = ' S'; <br />
print FILE "$time $flow $temp $salt\n";<br />
<br />
$time = ' dias';<br />
$flow = ' m3/s';<br />
$temp = ' C';<br />
$salt = ' psu';<br />
print FILE "$time $flow $temp $salt\n";<br />
<br />
print FILE "\n";<br />
<br />
$time = ' 1';<br />
$flow = ' 2';<br />
$temp = ' 3';<br />
$salt = ' 4';<br />
print FILE "$time $flow $temp $salt\n";<br />
<br />
print FILE "\n";<br />
<br />
$time = 'Tempo';<br />
$flow = ' Flow';<br />
$temp = ' T';<br />
$salt = ' S';<br />
print FILE "$time $flow $temp $salt\n";<br />
<br />
print FILE "<BeginTimeSerie>\n";<br />
<br />
$time = '99';<br />
$flow = 99;<br />
$temp = 99;<br />
$salt = 99;<br />
<br />
format FILE =<br />
@<<<< @###.##### @###.# @###.#<br />
$time, $flow, $temp, $salt<br />
.<br />
<br />
for (my $i=0; $i<$#$timev+1; $i++){ <br />
<br />
$time = $$timev[$i];<br />
$flow = $$runv[$i];<br />
$temp = $$tempv[$i];<br />
$salt = $$saltv[$i];<br />
write FILE;<br />
<br />
}<br />
<br />
print FILE "<EndTimeSerie>\n";<br />
<br />
# Close file<br />
close(FILE);<br />
<br />
}<br />
</code><br />
<br />
===Substitute pattern in file===<br />
#!/usr/local/bin/perl<br />
#This program substitutes the pattern "dd-mm-yyyy hh:mm:ss" from <br />
#argument file with "dd, mm, yyyy, hh, mm, ss".<br />
#The new text is then written in an output file.<br />
<br />
open FILE, "< @ARGV[0]";<br />
@text=<FILE>;<br />
close FILE;<br />
<br />
foreach $line (@text)<br />
{<br />
$line =~ s/(\S{1,2})-(\S{1,2})-(\S{4}) (\S{2}):(\S{2}):(\S{2})/$1, $2, $3, $4, $5, $6/g;<br />
push @newdata, $line;<br />
}<br />
<br />
open FILE, "> new_$ARGV[0]";<br />
print FILE @newdata;<br />
close FILE;<br />
<br />
===Send an e-mail===<br />
Here's a script that allows one to send e-mails.<br />
<code>[perl,Y]<br />
use Net::SMTP;<br />
<br />
$HOST = 'mail.ist.utl.pt';<br />
$FROM = 'my_address';<br />
$TO = 'his_address';<br />
$SUBJECT = 'SMTP perl test';<br />
@MESSAGE = ( <br />
"JAPH\n",<br />
"Maretec team\n",<br />
); <br />
$smtp = Net::SMTP -> new( Host => $HOST,<br />
Hello => $FROM,<br />
Timeout => 60,<br />
Debug => 1<br />
);<br />
$smtp -> mail($FROM);<br />
$smtp -> to($TO);<br />
@mail_content = ( "Subject: ".$SUBJECT."\n",<br />
"From: $FROM\n",<br />
"To: $TO\n",<br />
"\n"<br />
);<br />
push(@mail_content,@MESSAGE);<br />
$smtp -> data(@mail_content);<br />
$smtp -> quit();<br />
</code><br />
<br />
===FTP access===<br />
Here's a script to download from a remote ftp server<br />
<code>[perl,Y]<br />
use Net::FTP;<br />
<br />
$SERVER = 'your.server';<br />
$USER = 'you';<br />
$PASSW = 'yourpass';<br />
$FTP_DIR = 'yourdir';<br />
<br />
# Login and cd ( select binary mode ).<br />
$ftp = Net::FTP->new("$SERVER") || die "Can't communicate with $SERVER!";<br />
$ftp->login($USER, $PASSW) || die "Can't login $USER,$PASSW!";<br />
$ftp->binary || die "Can't change mode!";<br />
$ftp->cwd($FTP_DIR) || die "can't open $FTP_DIR";<br />
<br />
# Get the files list of the ftp.<br />
my @files = $ftp->ls();<br />
<br />
# Download the files list.<br />
foreach $file (@files){<br />
$ftp->get($file) || die "Can't download $file: ".$ftp->message."\n";<br />
print "Downloaded $file\n";<br />
}<br />
$ftp->quit();<br />
</code><br />
<br />
===rename files===<br />
Here's a sample file that renames all the files containing ''.f90'' to ''.F90''<br />
<code>[perl,Y]<br />
#!/usr/local/bin/perl<br />
#<br />
# Program to substitute $ren to $to for all files in the directory<br />
#<br />
<br />
use strict;<br />
<br />
$ren = ".f90";<br />
$to = ".F90";<br />
<br />
opendir(DIR,".");<br />
@text = readdir(DIR);<br />
foreach $line (@text)<br />
{<br />
if ($line =~ /$ren/)<br />
{<br />
@words = split(/ /, $line);<br />
foreach $word (@words)<br />
{<br />
if ($word =~ /$ren/)<br />
{ <br />
$word =~ s/\n//;<br />
push (@files, $word);<br />
}<br />
}<br />
}<br />
}<br />
closedir(DIR);<br />
<br />
foreach $file (@files)<br />
{<br />
$file2 = $file;<br />
$file2 =~ s/$ren/$to/;<br />
rename($file, $file2) || die "Can't rename ".$file;<br />
print "Changed ".$file." to ".$file2."\n";<br />
}<br />
</code><br />
<br />
===ConvertToHDF5===<br />
Here's another sample file that I use to automatically [[ConvertToHDF5]] all the compressed [[netcdf]] files in a given repository:<br />
<code>[perl,Y]<br />
#!/usr/local/bin/perl<br />
#<br />
#<br />
<br />
use strict;<br />
<br />
$DATE = '20060628';<br />
$IST = 'ist_meteog-mercatorPsy2v2r1v_R';<br />
$FOLDER = $IST . $DATE;<br />
$GZIP = gzip;<br />
$NC = ".nc";<br />
$CONVERT = "ConvertToHDF5";<br />
<br />
# 1 Uncompress them ###############<br />
<br />
chdir($FOLDER) or die "Can't chdir to ".$DIR;<br />
print 'Uncrunching ...\n';<br />
@args = ($GZIP, "-d", "\*\.gz");<br />
system(@args) == 0 or print "system @args failed: $?\n";<br />
<br />
opendir(DIR, ".");<br />
@text = readdir(DIR);<br />
foreach $line (@text)<br />
{<br />
if ($line =~ /$NC/)<br />
{<br />
@words = split(/ /, $line);<br />
foreach $word (@words)<br />
{<br />
if ($word =~ /$ren/)<br />
{ <br />
$word =~ s/\n//;<br />
push (@files, $word);<br />
}<br />
}<br />
}<br />
}<br />
print "Fetched ".@files." files.\n";<br />
chdir("..");<br />
<br />
# 2 Generate ConvertToHDF5Action ###############<br />
<br />
$action = 'ConvertToHDF5Action.dat';<br />
open(FILE, ">$action");<br />
my $TXT = << EndOfTXT;<br />
<br />
<begin_file><br />
ACTION : CONVERT MERCATOR FORMAT<br />
OUTPUTFILENAME : $FOLDER/MercatorR$DATE.hdf5<br />
OUTPUT_GRID_FILENAME : $FOLDER/MercatorGridR$DATE.dat<br />
INPUT_GRID_FILENAME : GridFiles/ist_meteog-gridT.nc<br />
INPUT_GRID_FILENAME_U : GridFiles/ist_meteog-gridU.nc<br />
INPUT_GRID_FILENAME_V : GridFiles/ist_meteog-gridV.nc<br />
OUTPUT_GEOMETRY_FILENAME : $FOLDER/MercatorGeometryR$DATE.dat<br />
<<begin_input_files>><br />
<br />
EndOfTXT;<br />
<br />
print FILE $TXT;<br />
<br />
foreach $file (@files)<br />
{<br />
print FILE $FOLDER."\/".$file."\n";<br />
}<br />
print FILE "<<end_input_files>>\n";<br />
print FILE "<end_file>\n";<br />
close(FILE);<br />
<br />
# 3 Run ConvertToHDF5 ###############<br />
<br />
print "Converting to HDF5...\n";<br />
@args = ($CONVERT);<br />
system(@args) == 0 or die "system @args failed: $?";<br />
print "Done ".@files." files.\n";<br />
<br />
# 4 Compress them back again ####################<br />
<br />
chdir($FOLDER) or die "Can't chdir to ".$DIR;<br />
print "Crunching back up...\n";<br />
@args = ($GZIP, "\*\.nc");<br />
system(@args) == 0 or die "system @args failed: $?";<br />
print "Finished ".@files." files.\n";<br />
</code><br />
<br />
==References==<br />
#The wikipedia [http://en.wikipedia.org/wiki/Perl_programming_language article].<br />
#A popular [http://www.comp.leeds.ac.uk/Perl/start.html tutorial].<br />
[[Category:Technology]]<br />
[[Category:Perl]]<br />
[[Category:Programming]]<br />
[[Category:Script]]<br />
[[Category:Linux]]<br />
[[Category:Windows]]</div>
89.180.146.64
http://wiki.mohid.com/index.php?title=Code&diff=110
Code
2008-03-15T01:10:33Z
<p>89.180.146.64: </p>
<hr />
<div>This wiki extension allows to embed code with pretty-colors.<br />
<br />
==Syntax==<br />
<br />
&lt;code&gt;[python,Y] ''insert python code here'' &lt;/code&gt;<br />
<br />
<code>[python,Y]<br />
#! /usr/bin/python<br />
""" A python primer. pydoc, doctest and classes.<br />
<br />
Syntax:<br />
To generate man pages:<br />
> pydoc classtemplate<br />
<br />
To try all the tests in doctest (and execute the script):<br />
> python classtemplate.py -v<br />
"""<br />
<br />
#Class definition<br />
class Table:<br />
"""Class Table.<br />
<br />
Doctest: here we insert python command lines inputs and outputs.<br />
>>> print Table.database<br />
http://access.com/db<br />
"""<br />
<br />
#Data attributes here<br />
database='http://access.com/db'<br />
<br />
#Method attributes here<br />
def __init__(self,id,text):<br />
"""Initializes the id and textlabel data attributes.<br />
<br />
Doctest: Testing more data attributes defined at construction time<br />
>>> x = Table(1,'coucou')<br />
>>> print x.id<br />
1<br />
>>> print x.textlabel<br />
coucou<br />
"""<br />
self.id=id<br />
self.textlabel=text<br />
<br />
#doctest -- "Debugging sucks :( Testing rocks :)"<br />
def _test():<br />
"""Inline Doctest activated. Cool! :D<br />
This means that whenever the module is called in python<br />
<br />
> python thismodule.py -v<br />
<br />
the doctest function will try all the tests implemented in doctest.<br />
"""<br />
import doctest<br />
doctest.testmod()<br />
<br />
if __name__ == "__main__":<br />
_test()<br />
</code><br />
<br />
[[Category:Wiki]]<br />
[[Category:Extension]]</div>
89.180.146.64